
正文
c运行python函数名 python c_void_p
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
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
相关问答
Q1: 求助 关于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;
}
Q2: python调用c函数
Python是解释性语言, 底层就是用c实现c运行python函数名的, 所以用python调用C是很容易c运行python函数名的, 下面就总结一下各种调用c运行python函数名的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过
1. Python 调用 C (base)
想在python中调用c函数, 如这儿的fact
#include Python.h
int fact(int n)
{
if (n = 1)
return 1;
else
return n * fact(n - 1);
}
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i:fact", n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};
void initexample()
{
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}
把这段代码存为wrapper.c, 编成so库,
gcc -fPIC wrapper.c -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config
然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)
2. Python 调用 C++ (base)
在python中调用C++类成员函数, 如下调用TestFact类中的fact函数,
#include Python.h
class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};
int TestFact::fact(int n)
{
if (n = 1)
return 1;
else
return n * (n - 1);
}
int fact(int n)
{
TestFact t;
return t.fact(n);
}
PyObject* wrap_fact(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i:fact", n))
return NULL;
result = fact(n);
return Py_BuildValue("i", result);
}
static PyMethodDef exampleMethods[] =
{
{"fact", wrap_fact, METH_VARARGS, "Caculate N!"},
{NULL, NULL}
};
extern "C" //不加会导致找不到initexample
void initexample()
{
PyObject* m;
m = Py_InitModule("example", exampleMethods);
}
把这段代码存为wrapper.cpp, 编成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config
然后在有此so库的目录, 进入python, 可以如下使用
import example
example.fact(4)
3. Python 调用 C++ (Boost.Python)
Boost库是非常强大的库, 其中的python库可以用来封装c++被python调用, 功能比较强大, 不但可以封装函数还能封装类, 类成员.
首先在ubuntu下安装boost.python, apt-get install libboost-python-dev
#include boost/python.hpp
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello)
{
using namespace boost::python;
def("greet", greet);
}
把代码存为hello.cpp, 编译成so库
g++ hello.cpp -o hello.so -shared -I/usr/include/python2.5 -I/usr/lib/python2.5/config -lboost_python-gcc42-mt-1_34_1
此处python路径设为c运行python函数名你的python路径, 并且必须加-lboost_python-gcc42-mt-1_34_1, 这个库名不一定是这个, 去/user/lib查
然后在有此so库的目录, 进入python, 可以如下使用
import hello
hello.greet()
'hello, world'
4. python 调用 c++ (ctypes)
ctypes is an advanced ffi (Foreign Function Interface) package for Python 2.3 and higher. In Python 2.5 it is already included.
ctypes allows to call functions in dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python.
#include Python.h
class TestFact{
public:
TestFact(){};
~TestFact(){};
int fact(int n);
};
int TestFact::fact(int n)
{
if (n = 1)
return 1;
else
return n * (n - 1);
}
extern "C"
int fact(int n)
{
TestFact t;
return t.fact(n);
}
将代码存为wrapper.cpp不用写python接口封装, 直接编译成so库,
g++ -fPIC wrapper.cpp -o example.so -shared -I/usr/include/python2.6 -I/usr/lib/python2.6/config
进入python, 可以如下使用
import ctypes
pdll = ctypes.CDLL('/home/ubuntu/tmp/example.so')
pdll.fact(4)
12
Q3: 请教高手,我在C/C++中嵌入python,用PyImport
#include iostream
#include Python.h
using namespace std;
void HelloWorld();
void Add();
void TestTransferDict();
void TestClass();
int main()
{
cout "Starting Test..." endl;
cout "HelloWorld()-------------" endl;
HelloWorld();
cout "Add()--------------------" endl;
Add();
cout "TestDict-----------------" endl;
TestTransferDict();
cout "TestClass----------------" endl;
TestClass();
system("pause");
return 0;
}
//调用输出"Hello World"函数
void HelloWorld()
{
Py_Initialize(); //使用python之前c运行python函数名,要调用Py_Initialize();这个函数进行初始化
PyObject * pModule = NULL; //声明变量
PyObject * pFunc = NULL; //声明变量
pModule =PyImport_ImportModule("Test001"); //这里是要调用的Python文件名
pFunc= PyObject_GetAttrString(pModule, "HelloWorld"); //这里是要调用的函数名
PyEval_CallObject(pFunc, NULL); //调用函数,NULL表示参数为空
Py_Finalize(); //调用Py_Finalize,这个和Py_Initialize相对应的.
}
//调用Add函数,传两个int型参数
void Add()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("Test001"); //Test001:Python文件名
pFunc= PyObject_GetAttrString(pModule, "add"); //Add:Python文件中的函数名
//创建参数:
PyObject *pArgs = PyTuple_New(2); //函数调用的参数传递均是以元组的形式打包的,2表示参数个数
PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 5));//0---序号 i表示创建int型变量
PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 7));//1---序号
//返回值
PyObject *pReturn = NULL;
pReturn = PyEval_CallObject(pFunc, pArgs); //调用函数
//将返回值转换为int类型
int result;
PyArg_Parse(pReturn, "i", result); //i表示转换成int型变量
cout "5+7 = " result endl;
Py_Finalize();
}
//参数传递的类型为字典
void TestTransferDict()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("Test001"); //Test001:Python文件名
pFunc= PyObject_GetAttrString(pModule, "TestDict"); //Add:Python文件中的函数名
//创建参数:
PyObject *pArgs = PyTuple_New(1);
PyObject *pDict = PyDict_New(); //创建字典类型变量
PyDict_SetItemString(pDict, "Name", Py_BuildValue("s", "WangYao")); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "Age", Py_BuildValue("i", 25)); //往字典类型变量中填充数据
PyTuple_SetItem(pArgs, 0, pDict);//0---序号 将字典类型变量添加到参数元组中
//返回值
PyObject *pReturn = NULL;
pReturn = PyEval_CallObject(pFunc, pArgs); //调用函数
//处理返回值:
int size = PyDict_Size(pReturn);
cout "返回字典的大小为: " size endl;
PyObject *pNewAge = PyDict_GetItemString(pReturn, "Age");
int newAge;
PyArg_Parse(pNewAge, "i", newAge);
cout "True Age: " newAge endl;
Py_Finalize();
}
//测试类
void TestClass()
{
Py_Initialize();
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule =PyImport_ImportModule("Test001"); //Test001:Python文件名
pFunc= PyObject_GetAttrString(pModule, "TestDict"); //Add:Python文件中的函数名
//获取Person类
PyObject *pClassPerson = PyObject_GetAttrString(pModule, "Person");
//创建Person类的实例
PyObject *pInstancePerson = PyInstance_New(pClassPerson, NULL, NULL);
//调用方法
PyObject_CallMethod(pInstancePerson, "greet", "s", "Hello Kitty"); //s表示传递的是字符串,值为"Hello Kitty"
Py_Finalize();
}
#test.py
def HelloWorld():
print "Hello World"
def add(a, b):
return a+b
def TestDict(dict):
print dict
dict["Age"] = 17
return dict
class Person:
def greet(self, greetStr):
print greetStr
#print add(5,7)
#a = raw_input("Enter To Continue...")
结果c运行python函数名:
配置c运行python函数名:
注意两点:
若编译Debug版c运行python函数名,请将C:/Python26/libs下的python26.lib复制一份改名为python26_d.lib
test.py 记得放项目的当前目录。
测试通过
Q4: 如何用python解析获取C源文件的函数名
class stdata(Structure):
_fields_ = [('pBuf', c_char_p), ('buflen', c_int)]
N=100
buf = create_string_buffer(N)
d = stdata()
d.buflen = N
d.pBuf = cast(buf, c_char_p)
n = CallMyCFunc_GetData(byref(d))
关键在于create_string_buffer创建可写buffer;cast转换为char*类型。
Q5: c如何调用python程序
C语言如何调用pythonc运行python函数名,相关步骤如下:
首先c运行python函数名,C语言中调用pythonc运行python函数名,要使用头文件Python.h。
2、接着,定义一个调用pythonc运行python函数名的函数。
相关推荐:《Python教程》
3、函数中,设置python库c运行python函数名的路径。
4、然后,初始化python。
5、运行一个python代码,输出How are you。
6、最后,释放python。
关于c运行python函数名和python c_void_p的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。






