Categories
Development

Error while using python file generated from SWIG (generated from C++)

I have a .cpp (called trial.cpp) file as follows:

   #include "trial.hpp"
   int main()
   {
        cout << "hello";
       return 0;
   }

My header file (trial.hpp) is:

#include <iostream>
using namespace std;

I have a .i file (trial.i) as follows:

%module trial
%{
#include "trial.hpp"
%}

%include trial.hpp

I have used SWIG in the following manner in cmd to generate .pyd, .py, .o and .cxx files:

swig -c++ -python trial.i

g++ -c trial_wrap.cxx -I C:\Users…..Python\Python37\include

g++ -shared trial_wrap.o -o _trial.pyd -L
C:\Users…..\Python\Python37\libs -l
python37

The files are generated successfully

However when I open Python command prompt and run this:

from trial import *

main()

I get an error saying

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

NameError: name ‘main’ is not defined

How can I resolve this issue?

Moreover, if I’m using another function name (say fn1()) instead of main(), I get the following error in the third command:

g++ -shared trial_wrap.o -o _trial.pyd -L
C:\Users…..\Python\Python37\libs -l python37

The error is:

undefined reference to fn1()

I’d like to use fn1() instead of main()

How can I solve this issue?

Leave a Reply

Your email address will not be published. Required fields are marked *