Wrapping a C++ class in Python using SWIG - c++

example.h:
#ifndef EXAMPLE_H
#define EXAMPLE_H
class Math {
public:
int pi() const;
void pi(int pi);
private:
int _pi;
};
#endif
example.cpp:
#include "example.h"
int Math::pi() const {
return this->_pi;
}
void Math::pi(int pi) {
this->_pi = pi;
}
example.swig:
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include "example.h"
I then generate the wrappers, "example.py" and "example_wrap.c" using:
swig -python example.swig
When I try to compile the wrapper class using:
g++ -fPIC -c example.cpp example_wrap.c -I/usr/local/include/python2.6/
I get the following error:
example_wrap.cpp: In function "PyObject* Swig_var_Math_get()":
example_wrap.cpp:2725: error: expected primary-expression before "void"
example_wrap.cpp:2725: error: expected ")" before "void"
The Error is at the following line :
pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&Math), SWIGTYPE_p_class, 0 );
#define SWIG_as_voidptr(a) (void *)((const void *)(a))
Is it the right way to generate the wrapper class "example_wrap.c"?

I think the swig command should be "swig -c++ -python example.swig"

There's not enough information here to be sure what's wrong, but I have two ideas for things you can try.
Your g++ invocation is compiling a C source file as if it were C++. This is not guaranteed to work. Try instead
gcc -I/usr/local/include/python2.6 -fPIC -c example_wrap.c
gcc -I/usr/local/include/python2.6 -fPIC -c example.cpp
g++ -shared example_wrap.o example.o -o example.so
(yes, srsly, only use g++ for the link)
If that doesn't work, compile example_wrap.c like this:
gcc -I/usr/local/include/python2.6 -fPIC -c -save-temps example_wrap.c
That will fail the same way but will produce a file named example_wrap.i which is the result of preprocesing. It will be gigantic. Search that file for the function Swig_var_Math_get, and add to your question the complete text of that function (but nothing else).

Thanks for your replay!
The -C++ option generated the C++ class for the wrapper.
swig -c++ -v -python example.swig
I used g++ to compile the wrapper.
g++ -fPIC -c example.cpp example_wrap.cxx -I/usr/local/include/python2.6/
And the following command to buikd the shared object. Ofcourse, we need to remove the superflous includes (-I) and libraries (-L). The important flags are '-shared' and '-fPIC'.
g++ example_wrap.o example.o -L/u01/app/oracle/product/1020.full/lib -I/usr/local/ssl/include -L/usr/local/ssl/lib -lclntsh -lssl -lcrypto -ldl -L/usr/local/lib -L/lib64 -L/usr/local/lib/python2.6/ -lboost_system -lboost_filesystem -lboost_thread -lboost_date_time -lglog -lmodpbase64 -lpthread -ldl -lrt -shared -fPIC -o _example.so

Related

How to solve redefinition of main in makefile

I am trying to compile and link three files into an executable with a makefile, but seem to have redefined main or somehow goofed the compile/link process. The project is for a class, where the objective is to implement a linear feedback shift register, but we have to use a makefile.
Where have I redefined main? How do I alter my makefile to create my executable? I notice the error points to test.o as having redefined main, but I'm not sure why or how.
Error:
g++ -c main.cpp LFSR.cpp -Wall -Werror -ansi -pedantic
g++ -c test.cpp -Wall -Werror -ansi -pedantic
g++ main.o LFSR.o test.o -o ps2a -lboost_unit_test_framework
test.o: In function `main':
test.cpp:(.text+0xa3): multiple definition of `main'
main.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
Makefile:4: recipe for target 'ps2a' failed
make: *** [ps2a] Error 1
My makefile:
all: ps2a
ps2a: main.o LFSR.o test.o
g++ main.o LFSR.o test.o -o ps2a -lboost_unit_test_framework
LFSR.o: LFSR.cpp LFSR.hpp
g++ -c LFSR.cpp -Wall -Werror -ansi -pedantic
main.o: main.cpp LFSR.hpp
g++ -c main.cpp LFSR.cpp -Wall -Werror -ansi -pedantic
test.o: test.cpp
g++ -c test.cpp -Wall -Werror -ansi -pedantic
clean:
rm *.o ps2a
main.cpp:
#include "LFSR.hpp"
int main(){
}
LFSR.hpp
#include <string>
#include <iostream>
class LFSR{
public:
LFSR(std::string, int);
int step();
int generate(int k);
private:
std::string bitString;
int tapPos;
};
LFSR.cpp:
#include "LFSR.hpp"
void makeBitStringValid(std::string& str);
LFSR::LFSR(std::string str, int t){
}
int LFSR::step(){
return 0;
}
int LFSR::generate(int k){
return 0;
}
void makeBitStringValid(std::string& str){
}
test.cpp (Note, this is given by the instructor-- I'm not entirely sure how it works yet)
#include <iostream>
#include <string>
#include "LFSR.hpp"
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(fiveBitsTapAtTwo) {
LFSR l("00111", 2);
BOOST_REQUIRE(l.step() == 1);
BOOST_REQUIRE(l.step() == 1);
BOOST_REQUIRE(l.step() == 0);
BOOST_REQUIRE(l.step() == 0);
BOOST_REQUIRE(l.step() == 0);
BOOST_REQUIRE(l.step() == 1);
BOOST_REQUIRE(l.step() == 1);
BOOST_REQUIRE(l.step() == 0);
LFSR l2("00111", 2);
BOOST_REQUIRE(l2.generate(8) == 198);
}
Do not provide own main because The Boost Unit Test Framework already provides one in your test.cpp with the lines:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
Dynamic library variant of the UTF
Unlike the static library variant function main() can't reside in the
dynamic library body. Instead this variant supplies default function
main() implementation as part of the header boost/test/unit_test.hpp
to be generated as part of your test file body. The function main() is
generated only if either the BOOST_TEST_MAIN or the BOOST_TEST_MODULE
flags are defined during a test module compilation. For single-file
test module flags can be defined either in a test module's makefile or
before the header boost/test/unit_test.hpp inclusion. For a multi-file
test module flags can't be defined in makefile and have to be defined
in only one of the test files to avoid duplicate copies of the
function main().

calling c++ function from c

I need to access a C++ function from C but I get some error like :-
/tmp/ccUqcSZT.o: In function `main':
main.c:(.text+0x5): undefined reference to `load_alert_to_db'
collect2: error: ld returned 1 exit status
My main.c code is:-
#include <stdio.h>
extern void load_alert_to_db(void);
int main(void){
/* Create empty queue */
load_alert_to_db();
return 0;
}
C++ code implementation db_manager.cpp is:-
#include <sstream>
#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <time.h>
#include <cstring>
#include <fstream>
//using namespace oracle::occi;
#include <iostream>
using namespace std;
extern "C" void load_alert_to_db(void)
{
cout<<"db occi"<<endl;
}
makefile is:-
CC= g++
all:
$(CC) -c -Wall -Werror -fPIC db_manager.cpp
$(CC) -shared -o libdb_manager.so db_manager.o
gcc -L/home/oracle/Desktop/storage/ -Wall main.c -o data -ldb_manager
gcc -o data main.c
clean:
rm -f *.o data
so please help me which one is my problem. I am also include
export LD_LIBRARY_PATH=/home/oracle/Desktop/storage/:$LD_LIBRARY_PATH
environmental variable in .bash_profile
gcc -o data main.c
Not sure why you have this line in your makefile since it will compile main.c without reference to the previously created library and hence cause an undefined-symbol error such as the one you're seeing.
This is especially so, since you appear to have done it the right way on the preceding line:
gcc -L/home/oracle/Desktop/storage/ -Wall main.c -o data -ldb_manager
However, the entire point of using makefiles is so that it figures out the minimum necessary commands for you, based on dependencies. Lumping a large swathe of commands into a single rule tends to defeat that purpose. You would be better off making your rules a little more targeted, such as (untested but should be close):
all: data
data: main.o libdb_manager.so
gcc -o data main.o -ldb_manager
main.o: main.c
gcc -o main.o main.c
libdb_manager.so: db_manager.cpp
g++ -c -Wall -Werror -fPIC -o db_manager.o db_manager.cpp
g++ -shared -o libdb_manager.so db_manager.o
That way, if you make a small change to one part (like main.c), it doesn't have to go and compile/link everything in your build tree.
Your makefile seems to be completely broken and random, and you're not even linking the required object files. You can simplify this:
all:
$(CC) -c -Wall -Werror -fPIC db_manager.cpp
$(CC) -shared -o libdb_manager.so db_manager.o
gcc -L/home/oracle/Desktop/storage/ -Wall main.c -o data -ldb_manager
gcc -o data main.c
to just this:
all:
gcc -Wall -c main.c
g++ -Wall -c db_manager.cpp
g++ main.o db_manager.o -o data
this is what I needed to do:
Supposing the C++ function is called Debug::Write(str)
Then in your hpp file do the following:
#ifdef __cplusplus
extern "C" void DebugTmp(char *str);
#endif
Then in the corresponding cpp file do this:
void DebugTmp(char *str)
{
Debug::Write(str);
}
Then in your C file where you call DebugTmp define the prototype:
void DebugTmp(char *str);
then call it as below:
static void MyFunction( void )
{
DebugTmp("This is debug trace\n");
}

C++ BOOST undefined reference to `boost::filesystem::detail::copy_file

I have no clue why boost::filesystem::copy_file is making trouble for me.
undefined reference to `boost::filesystem::detail::copy_file
// g++ -std=c++11 test.cpp -lboost_filesystem -lboost_system -lrt -lboost_wave
#include <boost/filesystem.hpp>
int main()
{
boost::filesystem::create_directory("aaa");
// ok
boost::filesystem::copy_file("f1","f2");
// /tmp/ccNWZltB.o: In function `boost::filesystem::copy_file(boost::filesystem::path const&, boost::filesystem::path const&)':
// test.cpp:(.text._ZN5boost10filesystem9copy_fileERKNS0_4pathES3_[_ZN5boost10filesystem9copy_fileERKNS0_4pathES3_]+0x26): undefined reference to `boost::filesystem::detail::copy_file(boost::filesystem::path const&, boost::filesystem::path const&, boost::filesystem::copy_option, boost::system::error_code*)'
// collect2: error: ld returned 1 exit status
return 0;
}
I got no inspiration from the source code of boost or its help:
inline
void copy_file(const path& from, const path& to, // See ticket #2925
BOOST_SCOPED_ENUM(copy_option) option, system::error_code& ec)
{detail::copy_file(from, to, option, &ec);}
Even such a simple example does not work for me.
Platform: Linux Ubuntu 64
There is a workaround for this problem, replace
#include <boost/filesystem.hpp>
with
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
#undef BOOST_NO_CXX11_SCOPED_ENUMS
Or, preferably, add -DBOOST_NO_CXX11_SCOPED_ENUMS to your compiler flags
If you run into this problem make sure to include both -lboost_system and -lboost_filesystem in your call to g++
Example working Makefile
BINARY = output
FILE_OBJECTS = main.o fileLoader.o
BOOST = -lboost_system -lboost_filesystem
GCC = g++ -std=c++17
FLAGS = -Wall -pedantic -Wextra
build: $(FILE_OBJECTS)
$(GCC) $(FLAGS) $(FILE_OBJECTS) -o $(BINARY) $(BOOST)
main.o: main.cpp fileLoader.o
$(GCC) $(FLAGS) -c main.cpp
fileLoader.o: fileLoader.cpp
$(GCC) $(FLAGS) -c fileLoader.cpp
clean:
rm -rf *.o $(BINARY)
Example working code
#include <boost/filesystem.hpp>
void create_data_file(std::string file_path)
{
boost::filesystem::path p(file_path);
boost::filesystem::create_directory(p);
}
I could not compile a file that included the header boost/filesystem.hpp either. This is how I solved it: I commented out the line boost/filesystem.hpp and all the lines that were using Boost, and then compiled the file. I then uncommented all the lines in the files and compiled again, and then it worked. I was compiling with the flag -lboost_system both times!
In older boost versions it is BOOST_NO_SCOPED_ENUMS, not BOOST_NO_CXX11_SCOPED_ENUMS
see boost::filesystem::copy_file() missing symbol in c++11

C++ shared library undefined reference

i'm having something like these files:
libfoo.h
class foo
{
public:
foo() = default;
virtual ~foo();
};
libfoo.cpp
#include "libfoo.h"
foo::~foo() { /* code here */ }
test.cpp
#include <libfoo.h>
int main()
{
foo f;
}
i compile libfoo.h and libfoo.cpp into a shared library and all that is fine.
but when i then try to use the library in test.cpp i get undefined reference to the destructor ~foo().
this error however does not occur if i define the destructor directly in libfoo.h. i have this problem with all functions defined outside the class in my library so im guessing it has something to do with the compilation process (it compiles fine however)
i compile the library like this:
g++ -std=c++0x -Wall -Werror -fPIC -c -o libfoo.o libfoo.cpp
g++ -shared libfoo.o -o libfoo.so
any ideas as to what i might be doing wrong?
(all the functions that i declare inclass, like template functions works fine and causes no undefined reference)
I tried to reproduce the error, but I failed.
I created the files (with slight modifications):
// libfoo.h
struct foo { virtual ~foo(); };
// libfoo.cpp
#include "libfoo.h"
foo::~foo() {}
// test.cpp
#include "libfoo.h"
int main() { foo f; }
Built like this:
$ g++ -std=c++0x -Wall -Werror -fPIC -c -o libfoo.o libfoo.cpp
$ g++ -shared libfoo.o -o libfoo.so
$ g++ test.cpp -L. -lfoo
And ran like this:
$ env LD_LIBRARY_PATH=. ./a.out
I got no errors. Are you sure there is a problem with your code?

resolved: c++ : put normal method definition into source file while the templates method in header file

Since the definition of template must be put in header file, so I don't like it if the template class is big. so I want to make a normal class with some templated methods. Putting the defintion of templated method into header file, for others, put them into c++ source files. So here is what I am thinking.
// lambda.h
#include <iostream>
class X {
public:
std::function<bool(int)> filter;
template <class F>
void setFilter(F fn) {
filter = fn;
}
void big_function(int x);
};
// cat lambda.cpp
#include <iostream>
#include "lambda.h"
void X::big_function(int x) {
if (filter(x)) std::cout << x << std::endl;
}
// main2.cpp
#include <stdlib.h>
#include "lambda.h"
class Filter {
public:
bool operator()(int x) { return true; }
};
int main() {
X x;
x.setFilter(Filter());
x.big_function(3);
return 0;
}
// cat 2.sh
g++ -c lambda.cpp -ggdb
g++ -c main2.cpp -ggdb -std=c++11
g++ -o main2 main2.o lambda.o -ggdb
this program can compile, but got segment fault during executing (x.big_function(3));
#update
Q1: is my thinking is reasonable? is there any obvious error in my code?
Answer: Yes, it is reasonable, and no obvious error. Thanks to the first 4 comments, I did more test and works.
Q2: actually if I compile with -std=c++11, I will got segment fault. but no segment fault if I don't use std=c++11. ( I tried c++11 yesterday because I used lambda expression rather than function object for "Filter" at beginning). And it my real case, I can't discard c++11 features.
Answer: shame about my fault. fixed the issue by adding -std=c++11 for every compile unit.
zhifan$ sh -x 2.sh
+ g++ -c lambda.cpp -ggdb
+ g++ -c main2.cpp -ggdb
+ g++ -o main2 main2.o lambda.o -ggdb
zhifan$ ./main2
3
zhifan$ vim 2.sh
hifan$ sh -x 2.sh
+ g++ -c lambda.cpp -ggdb **-std=c++11**
+ g++ -c main2.cpp -ggdb -std=c++11
+ g++ -o main2 main2.o lambda.o -ggdb
zhifan$ ./main2
Segmentation fault: 11
zhifan$ g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix