Python calls the C ++ code

C++

extern "C" {
float test_func (char *a, float b, int c); 
}
float test_func (char *a, float b, int c) {
    float d = 3.14;
    return d;
}

Compile a dynamic library

g++ pyclib.cpp -fPIC -shared -o libpyc.so

Python

from ctypes import *

pyclib = cdll.LoadLibrary('./libpyc.so')
pyclib.test_func.argtypes = [c_char_p, c_float, c_int]
pyclib.test_func.restype = c_float

a = 'c'
b = 1.0
c = 1
d = pyclib.test_func(a, b, c)

 

 

references:

https://www.jianshu.com/p/edb8698d1374

https://stackoverflow.com/questions/43317409/ctypes-argumenterror-dont-know-how-to-convert-parameter

https://docs.python.org/zh-cn/3.7/library/ctypes.html

https://docs.python.org/2/library/ctypes.html

 

Guess you like

Origin www.cnblogs.com/jhc888007/p/12378450.html