使用C API 实现C调Python 和python调C

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 ;
    }

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值