1. 程式人生 > >使用C API 實現C調Python 和python調C

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