提问者:小点点

Cython中C++外部变量的设置值


在我的项目中,我用Cython包装了一些C++代码(我完全控制这些代码),以便能够从Python调用C++功能。

在一个C++头文件中,我想使用“extern”关键字来定义(但不是初始化)一个变量,然后在相应的cpp实现文件中使用该变量。 我想在Cython包装器中设置该变量的值。

在下面的文章中,您可以找到我的代码的最小版本。

测试。h

extern int testVariable;

int getTestVariable();

test.cpp

#include "test.h"

int testVariable;

int getTestVariable() {
    return testVariable;
}

Wrapper.pxd

cdef extern from "test.h":

    int testVariable

    int getTestVariable()


testVariable = 42  # This does not seem to have any effect

cdef inline int test_function():
    print('testVariable = ' + str(testVariable))
    cdef int result = getTestVariable()
    print('result = ' + str(result))
    return result

当我调用Cython包装器函数test_function时,输出如下:

testVariable = 0
result = 0

似乎从未设置extern变量的值(它是0,但应该是42)。 有什么办法能让这起作用吗?

谢谢你的回答!

PS:我的代码受到https://stackoverflow.com/A/52925796的启发


共1个答案

匿名用户

我会使用类来解决这个问题,比如:

页眉

extern int m_nfoo;


class   __declspec(dllexport)  MyCppClass
{
public:
    MyCppClass();
    ~MyCppClass(void);

    int GetFoo();
    void SetFoo(int Foo);
....

C++:

int m_nFoo=0;


int MyCppClass::GetFoo()
{ 
    return m_nFoo;
}

void MyCppClass::SetFoo(int Foo)
{ 
    m_nFoo=Foo;
}

PXD:

cdef extern from "MyCppClass.h":

     
    cdef cppclass MyCppClass:
        MyCppClass()
        int GetFoo()
        void SetFoo(int Foo)

PYX:

cdef class myClass:
    """
    wrapper of MyCppClass
    """
       
    def __cinit__(self):
        self.thisptr = new MyCppClass()
        
    def setFoo(self,foo):
        self.thisptr.SetFoo(foo)
        
    def getFoo(self):
        return self.thisptr.GetFoo()   

在某些情况下:

    I=myClass()

    I.setFoo(42)
    print ('foo=',I.getFoo())

这很好用

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(cython|中|c++|外部|变量|设置|值)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?