简体   繁体   中英

wrapping C++ to Python with Swig on Mac OS X

I am trying to wrap simple c++ code by swig for python. My code is
hello.cpp

#include <iostream>
/*simple function for trying swig*/
char const* greet(){
    return "hello world!";
}

wrapper code helloworld.i

/*interface file for swig : corresponds to hello.cpp*/
%module helloworld
%{
/*headers and declarations here*/
extern char const* greet();
%}
extern char const* greet();

The commands I used :

swig -c++ -python helloworld.i
g++ -O2 -fPIC -c hello.cpp
g++ -O2 -fPIC -c helloworld_wrap.cxx -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7
g++ -lpython -dynamclib hello.o helloworld_wrap.o -o _helloworld.so

The first three commands work well and produce all the files needed but the last command gives the following error.

Error message:

clang: warning: argument unused during compilation: '-dynamclib'
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see     invocation)

What is going wrong here? I am very confused with this.

Use -dynamiclib instead of -dynamclib .

EDIT (answering your comment below):

I can reproduce the error

Fatal Python error: PyThreadState_Get: no current thread
Abort trap: 6

if I try to import the module from a different python than it was linked against.

You are linking against the system python, so you should use that. Try:

/usr/bin/python
>>> import helloworld
>>> helloworld.greet()

Probably you have another python version installed somewhere. Do which python to see which version is being called.

Now, to link against the correct python, you can either use python-config to determine the correct compiler arguments, or write a small setup.py file and let distutils handle the compilation (probably the best way to go).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM