下面的cpp代码摘自极客网站:
#include <iostream>
class Geek{
public:
static int i;
void myFunction(){
(Geek::i)++;
std::cout << "Hello Geek!!!" << Geek::i << std::endl;
}
};
int Geek::i=0;
int main()
{
// Creating an object
Geek t;
// Calling function
t.myFunction();
return 0;
}
extern "C" {
Geek* Geek_new(){ return new Geek(); }
void Geek_myFunction(Geek* geek){ geek -> myFunction(); }
}我编译了它并使用以下命令创建了so文件: g++ -c -fPIC foo.cpp -o foo.o g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
并从python部分调用so文件:
# import the module
from ctypes import cdll
# load the library
lib = cdll.LoadLibrary('./libfoo.so')
# create a Geek class
class Geek(object):
# constructor
def __init__(self):
# attribute
self.obj = lib.Geek_new()
self.obj2 = lib.Geek_new()
# define method
def myFunction(self):
lib.Geek_myFunction(self.obj)
lib.Geek_myFunction(self.obj2)
# create a Geek class object
f = Geek()
# object method calling
f.myFunction()
f.myFunction()当我运行这段代码时,我得到以下错误:./libfoo.so:未定义符号:_ZN4Geek1iE
如果我将静态变量放在函数中并编译它,它可以正常工作,但我需要该变量成为类的静态成员。
要使它发挥作用,需要做些什么?
update 我已经根据tevemadar更新了代码,并且成功了。我需要初始化GEEK::我在类之外
发布于 2022-02-23 09:40:55
感谢特维玛达的回答。我们是GEEK::i,而不是班上的i。并在类之外初始化它。
int GEEK::i = 0;更新的代码可以在问题中看到。
https://stackoverflow.com/questions/71234130
复制相似问题