[使用cython和cythonize从python调用C ++

问题描述 投票:0回答:1

我正在尝试学习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"))
python c++ cython cythonize
1个回答
0
投票
[也许是,您明确的定义为“ clear C”的功能正在帮助您。在任何情况下,错误消息都会指定此功能类型。试试这个:

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

© www.soinside.com 2019 - 2024. All rights reserved.