C调用Python
#include<Python.h>
int main()
{
Py_Initialize();//初始化Python解释器
if (!Py_IsInitialized())
{
printf("Initialize failed");
return -1;
}
PyRun_SimpleString("print('hello C !')");
PyRun_SimpleString("import pytest");
PyRun_SimpleString("pytest.printTime()");
Py_Finalize();//关闭Python解释器
return 0;
}
编译
gcc -Wall -I /usr/include/python3.9 -lpython3.9 python.c
Python调用C [ctypes]
// test.c
long long run(long long n) {
long long s = 0;
for (long long i=0;i<n;i++) {
s += i;
}
return s;
}
gcc -shared -o test.o test.c
from ctypes import cdll,c_longlong,Structure
class c_longlong_type(Structure):
_fields_ = [("p", c_longlong)]
test = cdll.LoadLibrary("./test.so")
test.run.restype=c_longlong_type
test.run(100_000_000)
传参
from ctypes import *
w = cdll.LoadLibrary("./a.so").weather
address = create_string_buffer("广州市".encode())
output = create_string_buffer(10240)
w(address, output)
print(output.value.decode())