c/c++再學習:C與Python相互調用

###c/c++再學習:Python調用C函數 Python 調用C函數比較簡單 這裏兩個例子,一個是直接調用參數,另外一個是調用結構體 C代碼python

typedef struct {
	int i1;
	int i2;
	char str[20];
} core_data_t;

__declspec(dllexport) int add(int a, int b)
{
	return a + b;
}

__declspec(dllexport) int multi(int a, int b)
{
	return a * b;
}

__declspec(dllexport) int struct_add(core_data_t* data)
{
	printf("%s\n", data->str);
	return data->i1 + data->i2;
}

python代碼c++

from ctypes import *

core = CDLL('core.dll')

add_val = core.add(1, 2)
multi_val = core.multi(2, 3)

print(add_val)
print(multi_val)

class CoreData(Structure):
    _fields_ = [("i1", c_int),
                ("i2", c_int),
                ("str", c_char*20)]

coredata = CoreData()
coredata.i1 = 10
coredata.i2 = 20
coredata.str = b"hello world"
coredata_ptr = byref(coredata)
struct_add_val = core.struct_add(coredata_ptr)

print(struct_add_val)

結果windows

3
6
30
hello world

###C調用python函數函數

c調用python,須要在增長<Python.h>和python36.lib,有時遇到編譯時須要python36_d.lib時,只須要將python36.lib複製重命名爲python36_d.lib放在同目錄下便可學習

python代碼ui

def py_print():
    print("py_print")

def py_add(a,b):
    return a+b

c代碼code

#include "stdio.h"
#include "windows.h"
#include <Python.h>   

void main()
{
	Py_Initialize();                  
	PyObject* pModule = NULL;        
	PyObject* pFunc = NULL;        
	PyObject* pArgs = NULL;
	PyObject* pValue = NULL;

	pModule = PyImport_ImportModule("python_demo");          
	pFunc = PyObject_GetAttrString(pModule, "py_print");   
	PyEval_CallObject(pFunc, NULL);   

	pFunc = PyObject_GetAttrString(pModule, "py_add");
	pArgs = PyTuple_New(2);

	PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 5));
	PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 10));

	pValue = PyEval_CallObject(pFunc, pArgs);
	int res = 0;
	PyArg_Parse(pValue, "i", &res);
	printf("res %d\n", res);

	Py_Finalize();   
	return;
}

結果it

py_print
res 15
相關文章
相關標籤/搜索