贡献者: addis
extern "C" {}
定义要导出的函数(可以只是简单把 cpp 函数和对象封装一下,但不能使用相同的函数名否则编译器会报错)。
int myfun_imp() {
return 123456;
}
extern "C" {
int myfun() { return myfun_imp(); }
}
test.so
):g++ -shared -fPIC -o test.so test.cpp
os.getcwd()
from ctypes import cdll
lib = cdll.LoadLibrary('./test.so')
lib.myfun()
就会返回 123456
了!
void cfun(const double *indatav, size_t size, double *outdatav)
{
size_t i;
for (i = 0; i < size; ++i)
outdatav[i] = indatav[i] * 2.0;
}
import ctypes
from numpy.ctypeslib import ndpointer
lib = ctypes.cdll.LoadLibrary("./ctest.so")
fun = lib.cfun
fun.restype = None
fun.argtypes = [ndpointer(ctypes.c_double, flags="C_CONTIGUOUS"),
ctypes.c_size_t,
ndpointer(ctypes.c_double, flags="C_CONTIGUOUS")]
indata = numpy.ones((5,6))
outdata = numpy.empty((5,6))
fun(indata, indata.size, outdata)
 
 
 
 
 
 
 
 
 
 
 
友情链接: 超理论坛 | ©小时科技 保留一切权利