从python调用C++函数,使用cython,使用cythonize

Calling a C++ function from python, using cython, with cythonize

本文关键字:使用 cythonize cython 函数 python 调用 C++      更新时间:2023-10-16

我正在尝试学习Cython,我想从python调用一个简单的C++函数

构建时,我要么有一个uio.obj : error LNK2001: unresolved external symbol _just_a_func,要么当我尝试不同的cython原型组合时,我的just_a_func((函数没有落在我的模块中。

这是所有代码,setup.py,test.py,.pxd,.pyx和.h

########################
### uio.h
########################
#include <string>
using namespace std;
struct uio{
int i;
uio():i(2){}
float f;
string s;
// float fun(int a);
float fun(int a){return float(a+i);}
};
// int just_a_func(string s);
int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string
cdef extern from "uio.h":
cdef extern int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++
from uio cimport just_a_func
cdef extern int just_a_func(s):
return just_a_func(s)

########################
### setup.py
########################
# python .setup.py build_ext --inplace --compiler=msvc
from setuptools import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("uio.pyx"))
########################
### test2.py
########################
import uio
print(dir(uio))
print("just_a_func", uio.just_a_func("fdsfds"))

可能是,将你的函数显式定义为"clear C"正在帮助你。在任何情况下,您的错误消息都会指定该类型的函数。试试这个:

extern "C" {
int just_a_func(string s){return s.length();}
}

在 https://dmtn-013.lsst.io/上找到了解决方案

这是可行的解决方案

########################
### uio.h
########################
#include <string>
using namespace std;
int just_a_func(string s){return s.length();}

########################
### uio.pxd
########################
from libcpp.string cimport string
cdef extern from "uio.h":
int just_a_func(string s)

########################
### uio.pyx
########################
# distutils: language = c++
# note the "as", this is a trick to avoid name clash, to allow the same function name
from uio cimport just_a_func as cjust_a_func
def just_a_func(s):
return cjust_a_func(s)

########################
### setup.py
########################
# python .setup.py build_ext --inplace --compiler=msvc
from setuptools import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("uio.pyx"))
########################
### test2.py
########################
import uio
from sys import argv
print(dir(uio))
print("just_a_func", uio.just_a_func((argv[1].encode())))