从python调用C++函数,使用cython,使用cythonize
Calling a C++ function from python, using cython, with cythonize
我正在尝试学习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())))
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 使用新行和不使用新行读取文件
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何确定我已使用非编码文件到达 EOF?
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 使用CMake创建QML插件
- 使用strcpy将char数组的元素复制到另一个数组
- 在c++中使用nlohmann从类到json的转换
- 使用指针从C++中的数组中获取最大值
- 从python调用C++函数,使用cython,使用cythonize