c调python函数 c++怎么调用python函数

C语言程序如何调用python程序

下面是一个例子:

成都创新互联公司网站建设公司,提供成都网站设计、做网站、成都外贸网站建设公司,网页设计,建网站,PHP网站建设等专业做网站服务;可快速的进行网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,是专业的做网站团队,希望更多企业前来合作!

首先是python的一个简单函数

class Hello:

def __init__(self, x):

self.a = x

def print(self, x=None):

print(x)

def xprint():

print("hello world")

if __name__ == "__main__":

xprint()

h = Hello(5)

h.print()1

下面是C语言

#include python3.4m/Python.h

#include stdio.h

#include stdlib.h

#include string.h

int main()

{

Py_Initialize();

// 将当前目录加入sys.path

PyRun_SimpleString("import sys");

PyRun_SimpleString("sys.path.append('./')");

// 导入hello.py模块

PyObject *pmodule = PyImport_ImportModule("hello");

// 获得函数xprint对象,并调用,输出“hello world\n”

PyObject *pfunc = PyObject_GetAttrString(pmodule, "xprint");

PyObject_CallFunction(pfunc, NULL);

// 获得类Hello并生成实例pinstance,并调用print成员函数,输出“5 6\n”

PyObject *pclass = PyObject_GetAttrString(pmodule, "Hello");

PyObject *arg = Py_BuildValue("(i)", 5);

PyObject *pinstance = PyObject_Call(pclass, arg, NULL);

PyObject_CallMethod(pinstance, "print", "i", 6);

Py_Finalize();

return 0;

}

编译命令如下:

gcc pyapi.c -lpython3.4m -o pyapi

c/c++调用python中返回值为list的函数

在C/C++中调用了这个函数之后不是会返回一个PyObject对象吗?那个对象就是一个List啊,然后使用PyList_Size()获取它的大小,使用PyList_GetItem()去读取其中的元素就ok了啊。

找下Python的C API Manual,里面这些函数的用法写的很详细的。

我在C++中调用python写的函数为什么不行?

可以具体说一下是怎么调用的吗,像我使用C/C++调用这个外部程序(例如Python程序)时,我是这么做的,通过命令行参数通信,给个模板,注意看我的注释。

C的部分(用C++也行,不过不难,也不是重点):

#includestdlib.h

#includestdio.h

int main(){

char pic_dir[255],pic_dir[255],cmd[255];

printf("What is your pic_dir? (e.g. C:\\a.jpg)\n");

/*虽然我强烈认为命名上应该不用pic_dir而是用pic_path*/

scanf("%s",pic_dir);

printf("What is your pic_name?(e.g. b.jpg)\n");

scanf("%s",pic_name);

printf("so we are calling a python program to deal with those above, please wait...\n");

sprintf(cmd,"python process.py %s %s ",pic_dir,pic_name);

/*这里是一个关键点,python的运行目录在你的PATH环境变量里有,如下图最后一行*/

system(cmd);

return 0;

}

process.py:(部分内容,主要是在process方法定义后面加一点东西)

def process(pic_dir,pic_name):

...#(这里的语句体(suite)不用改, 加上后面两句就行)

from sys import argv

process(argv[1],argv[2])

OK完成

如何在C语言中调用python函数

C语言不能直接调用Python源程序,但是可以通过进程调用来实现。


分享文章:c调python函数 c++怎么调用python函数
网站网址:http://scyanting.com/article/hhhieo.html