mardi 31 mars 2015

How to use shared_ptr in extern C when use python to call the so file?

I want to use C++ to make an so file on Linux,and use python to call the library.I use shared_ptr in extern C declare,compile success but get some error when call the library use python. I create some cpp files,like these: Calculator.h:



#ifndef HELLO_WORLD_CALCULATOR_H
#define HELLO_WORLD_CALCULATOR_H
class Calculator {
public:
double add(double first, double second);
};
#endif


Calculator.cpp:



#include "Calculator.h"
double Calculator::add(double first, double second) {
return first + second;
}


main.cpp:



#include <iostream>
#include <tr1/memory>
#include "Calculator.h"

using namespace std;

double devide1(double first, double second){
shared_ptr<Calculator>calculater(new Calculator());
return calculater->devide(first, second);
}

extern "C"
{
double devide(double f, double s){
return devide1(f,s);
}
}


And I compile the file use this command: g++ main.cpp -fPIC -shared -o test.so -std=c++11 My python file test.py:



# coding=utf-8

import ctypes
from ctypes import *

if __name__ == "__main__":
lib = ctypes.CDLL("./test.so")
lib.devide.argstype = [c_double, c_double]
lib.devide.restype = c_double
print lib.devide(c_double(12), c_double(36))


And I run the program use python test.py in terminal.Then I got the error:



Traceback (most recent call last):
File "test.py", line 9, in <module>
lib = ctypes.CDLL("./test.so")
File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
OSError: ./test.so: undefined symbol: _ZN10Calculator6devideEdd


How to fix the bug?


Aucun commentaire:

Enregistrer un commentaire