资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

c导入python函数 如何将python代码转为C

c如何调用python程序

C语言如何调用python,相关步骤如下:

成都创新互联公司专注于站前企业网站建设,响应式网站建设,商城建设。站前网站建设公司,为站前等地区提供建站服务。全流程按需网站建设,专业设计,全程项目跟踪,成都创新互联公司专业和态度为您提供的服务

首先,C语言中调用python,要使用头文件Python.h。

2、接着,定义一个调用python的函数。

相关推荐:《Python教程》

3、函数中,设置python库的路径。

4、然后,初始化python。

5、运行一个python代码,输出How are you。

6、最后,释放python。

怎样把Python代码嵌入到C程序

这篇文章主要介绍了将Python代码嵌入C++程序进行编写的实例,尽管通常还是Python代码中调用C++程序的情况较多...需要的朋友可以参考下

把python嵌入的C++里面需要做一些步骤

安装python程序,这样才能使用python的头文件和库

在我们写的源文件中增加“Python.h”头文件,并且链入“python**.lib”库(还没搞清楚这个库时静态库还是导出库,需要搞清楚)

掌握和了解一些python的C语言api,以便在我们的c++程序中使用

常用的一些C API函数

在了解下面的函数之前有必要了解一下**PyObject***指针,python里面几乎所有的对象都是使用这个指针来指示的。

Py_Initialize()Py_Finalize()

在调用任何python的c函数之前需要调用的函数,“Py_Initialize”是用来初始化python模块的,推测是加载初始化加载dll的。对应的在使用python模块之后用“Py_Finalize”来释放模块。

PyImport_ImportModule()

用来载入一个python模块,这个模块就是一般的python文件。这里需要注意的是,在加载这个模块的时候会执行模块里面所有可以执行的语句。包括import导入语句和在函数体之外的所有语句

PyObject_GetAttrString()

返回模块里面的函数

Py_BuildValue()

建立一个参数元组,一般都是用这个函数来建立元组,然后将这个元组作为参数传递给python里面的函数。

PyEval_CallObject()

调用函数,并把“Py_BuildValue”建立的元组作为参数传递给被调用的函数

源码实例

下面的实例是在c++代码中调用Python的函数,传递参数并且获取返回值

test.cpp代码

[cpp] view plain copy

#include iostream

#include Python.h

using namespace std;

int main(int argc, char* argv[])

{

Py_Initialize();  //初始化

PyObject* pModule = NULL;

PyObject* pFunc = NULL;

PyObject* pParam = NULL;

PyObject* pResult = NULL;

const char* pBuffer = NULL;

int iBufferSize = 0;

pModule = PyImport_ImportModule(“test_python");

if (!pModule)

{

cout  "get module failed!"  endl;

exit (0);

}

pFunc = PyObject_GetAttrString(pModule, "main");

if (!pFunc)

{

cout  "get func failed!"  endl;

cout  int(pFunc)  endl;

exit (0);

}

pParam = Py_BuildValue("(s)", "HEHEHE");

pResult = PyEval_CallObject(pFunc,pParam);

if(pResult)

{

if(PyArg_Parse(pResult, "(si)", pBuffer, iBufferSize))

{

cout  pBuffer  endl;

cout  iBufferSize  endl;

}

}

Py_DECREF(pParam);

Py_DECREF(pFunc);

Py_Finalize();

//cout  "hello"  endl;

return 0;

}

test_python.py代码

[py] view plain copy

def main(szString):

return ("hello", 5)

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

下面是一个例子:

首先是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

python怎么导入自定义函数

这个问题涉及到包和模块管理。包名和模块名一般是小写。你的文件是下面的结构,需要创建空文件 b/__init__.py,将b目录变成package。a/a.py

12

from b.c import indexindex()

b/c.py

12

def index(): print("hello")

b/__init__.pya/a.py 里面有两种引用方式,相对引用和绝对引用:# 如果a.py是 library,两种引用方式都可以

1

from ..b.c import index

# 如果a.py是 executable,必须使用绝对引用

1

from b.c import index

如果使用绝对引用,需要确保b所在目录在PYTHONPATH (sys.path)里面,比如可以这样执行:

1

env PYTHONPATH=. python a/a.py

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

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

求助 关于c程序中嵌入Python的问题

嵌入

与python的扩展相对,嵌入是把Python解释器包装到C的程序中。这样做可以给大型的,单一的,要求严格的,私有的并且(或者)极其重要的应用程序内嵌Python解释器的能力。一旦内嵌了Python,世界完全不一样了。

C调用python中的函数:

hw.py:

#coding=utf8

def hw_hs(canshu):

return canshu

if __name__ == "__main__":

ccss = "I am hw"

print hw_hs(ccss)

helloWorld.py:

#coding=utf8

import hw

def hello():

ccss = "I am helloWorld"

return hw.hw_hs(ccss)

if __name__ == "__main__":

print hello()

testcpypy.c:

//#include "testcpypy.h"

#include Python.h

#include stdio.h

#include stdlib.h

int main()

{

//初始化Python

Py_Initialize();

if (!Py_IsInitialized()) {

printf("Py_Initialize");

getchar();

return -1;

}

//执行python语句

PyRun_SimpleString("import sys");

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

PyObject *pModule = NULL;

PyObject *pFunc = NULL;

PyObject *reslt =NULL;

//载入python模块

if(!(pModule = PyImport_ImportModule("helloWorld"))) {

printf("PyImport_ImportModule");

getchar();

return -1;

}

//查找函数

pFunc = PyObject_GetAttrString(pModule, "hello");

if ( !pFunc || !PyCallable_Check(pFunc) )

{

printf("can't find function [hello]");

getchar();

return -1;

}

//调用python中的函数

reslt = (PyObject*)PyEval_CallObject(pFunc, NULL);

//printf("function return value : %d\r\n", PyInt_AsLong(reslt));

//将python返回的对象转换为C的字符串

char *resltc=NULL;

int res;

res = PyArg_Parse(reslt, "s", resltc);

if (!res) {

printf("PyArg_Parse");

getchar();

return -1;

}

printf("resltc is %s", resltc);

getchar();

//释放内存

Py_DECREF(reslt);

Py_DECREF(pFunc);

Py_DECREF(pModule);

//关闭python

Py_Finalize();

return 0;

}

编译:

gcc -o testcpypy testcpypy.c -IC:\Python27\include -LC:\Python27\libs -lpython27 ---C:\Python27为python安装目录

或:

gcc -c testcpypy.c -IC:\Python27\include

gcc -o testcpypy.exe testcpypy.o -LC:\Python27\libs -lpython27

执行结果:

带参数的情况:

#include "callpydll.h"

#include "Python.h"

#include stdio.h

#include stdlib.h

#include string.h

#include stdarg.h

int callhello(char *instr, char *outstr)

{

PyObject *pModule = NULL;

PyObject *pFunc = NULL;

PyObject *reslt = NULL;

PyObject *pParm = NULL;

char *resltc = NULL;

int resltn;

int res;

char *helloWorld = "TestIM_ProtocBuf";

char *im_account = "aaaa";

char *auth_code = "aaaa";

char *im_uid = "aaaa";

char *proxy_topic = "";

//初始化Python

Py_Initialize();

if (!Py_IsInitialized()) {

printf("Py_Initialize");

getchar();

return -1;

}

//执行python语句

PyRun_SimpleString("import sys");

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

//载入python模块

if(!(pModule = PyImport_ImportModule(helloWorld))) {

printf("PyImport_ImportModule");

getchar();

return -2;

}

//查找函数

pFunc = PyObject_GetAttrString(pModule, "login_proxy_body_serialize");

if ( !pFunc || !PyCallable_Check(pFunc) )

{

printf("can't find function [hello]");

getchar();

return -3;

}

//参数转换C -- python, 参数必须是元组(一个参数也是,否则会失败!!!坑啊)

pParm = Py_BuildValue("(ssss)", im_account, auth_code, im_uid, proxy_topic);

//调用python中的函数

reslt = (PyObject*)PyEval_CallObject(pFunc, pParm);

//将python返回的对象转换为C的字符串

res = PyArg_ParseTuple(reslt, "si", resltc, resltn);

if (!res) {

printf("PyArg_Parse");

getchar();

return -4;

}

printf("resltn is %d", resltn);

memcpy(outstr, resltc, strlen(resltc)+1);

//释放内存

Py_DECREF(reslt);

Py_DECREF(pFunc);

Py_DECREF(pModule);

Py_DECREF(pParm);

//关闭python

Py_Finalize();

return 0;

}

int main() {

int i;

char *dais = "iammain";

char res[10240];

memset(res,'\0',sizeof(res));

i = callhello(dais, res);

if(0 != i) {

printf("Notify:error");

getchar();

return -1;

}

printf("result is %s", res);

getchar();

return 0;

}


网站栏目:c导入python函数 如何将python代码转为C
文章起源:http://cdkjz.cn/article/hpdpoi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220