I am trying to write a math library in c++ for a game I made in python. I tried following the steps from answer by Florian Bosch in this question.
My operating system is windows 10. Here is the code in c++
#include <iostream>
struct Math
{
void print()
{
std::cout << "hehe" << std::endl;
}
};
extern"C"
{
Math* newMath()
{
return new Math();
}
void math_print(Math* math)
{
math->print();
}
}
Code in python
from ctypes import cdll
lib = cdll.LoadLibrary('./math.so')
class Math:
def __init__(self):
self.object = lib.newMath()
def print(self):
lib.print = (self.object)
math = Math()
math.print()
Compilation of .o and .so files
g++ -c -fPIC math.cpp -o math.o
g++ -shared -Wl,-soname,math.so -o math.so math.o
Error message
self._handle = _dlopen(self._name, mode)
OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed
Both my python interpreter and g++ compiler are 64 bits.
After n.'pronouns'm's comment about linkers, I decided to remove the #include<iostream>
from c++ file to see what happens, and it sort of worked.
I changed the c++ code to
//#include <iostream>
struct Math
{
int print()
{
return 5;
}
};
extern"C"
{
Math* newMath()
{
return new Math();
}
void math_print(Math* math)
{
math->print();
}
and python code to
from ctypes import cdll
lib = cdll.LoadLibrary('./math.so')
class Math:
def __init__(self):
self.object = lib.newMath()
def print(self):
lib.math_print = (self.object)
math = Math()
print(math.print())
I would expect it to print 5, but it prints none
and no error this time. I will also definitely need libraries in the future to access the math functions.