Python调C
python 调C语言主要是将C代码编译成so文件,通过python端的ctypes导入C库使用C函数,简单使用如下
void TestLib::hello(int a) {
printf("hello world");
}
extern "C" {
void hello();
}
python 端
import ctypes
so = ctypes.cdll.LoadLibrary
lib = so("./libhello.so")
print 'hello()'
lib.hello(100)
C端调用Pyhton
Py_Initialize(); // 启动虚拟机
if (!Py_IsInitialized())
return -1;
// 导入模块
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
pModule = PyImport_ImportModule("PythonPlugin");
if (!pModule) {
printf("Cant open python file!/n");
return;
}
//获取celue类
// 模块的字典列表
pDict = PyModule_GetDict(pModule);
if (!pDict) {
printf("Cant find dictionary./n");
return;
}
PyObject* pClassPerson = PyDict_GetItemString(pDict, "PythonPlugin");
if (!pClassPerson) {
printf("Cant find PythonPlugin class./n");
return;
}
strategy = PyDict_GetItemString(pDict, "Strategy");
if (!strategy) {
printf("Cant find Strategy class./n");
return ;
}
//构造策略的实例
strategy_plugin = PyInstance_New(pClassPerson, NULL, NULL);
if (!strategy_plugin) {
printf("Cant find person instance./n");
return ;
}
//调用Pyhton成员函数
PyObject*str = PyObject_CallMethod(strategy_plugin, "OnInit", "s","百度搜索");
if(!str){
PyErr_Print();
printf("Cant find Strategy OnInit\n");
return;
}
//调用python函数
PyObject_CallFunction(pFunHi, "s", "lhb");
将c函数导入pyhton供python使用
int hello(int n)
{
printf("hello")
return 1;
}
PyObject* wrap_hello(PyObject* self, PyObject* args)
{
int n, result;
if (! PyArg_ParseTuple(args, "i:hello", &n))
return NULL;
result = hello(n);
return Py_BuildValue("i", result);
}
static PyMethodDef helloMethods[] =
{
{"hello", wrap_hello, METH_VARARGS, "hello"},
{NULL, NULL}
};
void inithello()
{
PyObject* h;
h = Py_InitModule("hello", helloMethods);
}
使用如下:
int main(){
Py_Initialize(); // 启动虚拟机
if (!Py_IsInitialized())
return -1;
// 导入模块
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
initexample();
PyObject* pModule = PyImport_ImportModule("hello");
if (!pModule) {
printf("Cant open python file!\n");
return -1;
}
// 模块的字典列表
PyObject* pDict = PyModule_GetDict(pModule);
if (!pDict) {
printf("Cant find dictionary./n");
return -1;
}
PyObject* pFunHi = PyDict_GetItemString(pDict, "fun3");
PyObject_CallFunction(pFunHi, "s", "lhb");
Py_DECREF(pFunHi);
return 0;
}
import example
def fun3(ss):
example.fact(4)
print ("fun3")
Pyhton Dict的使用
PyObject* pArgsD = PyDict_New();
PyDict_SetItemString(pArgsD, "id", Py_BuildValue("s", info->info->id));
PyDict_SetItemString(pArgsD, "market", Py_BuildValue("i", info->info->market));
PyDict_SetItemString(pArgsD, "name", Py_BuildValue("s", info->info->name));
PyDict_SetItemString(pArgsD, "tick", Py_BuildValue("i", info->info->price_tick));
PyObject*level_str = PyObject_CallMethod(strategy, "OnInit", "O", pArgsD);
if(!level_str){
PyErr_Print();
printf("Cant find Strategy OnInit\n");
return ;
}