Python与C交互

cooolr 于 2022-08-03 发布

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

引用.so

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)

Python%E4%B8%8EC%E4%BA%A4%E4%BA%92%20963f2609bd44470985058cc905dcd522/-54c1a517389fe762.jpg

传参

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())