I am new to C++, so apologies for any 'silly' mistakes.
I have created a shared object in C++ for use in Python. However, when I try to call this function in Python, the kernel crashes.
The C++ file is as follows:
#include <cmath>
#include <iostream>
#include <list>
#include <vector>
using namespace std;
extern "C"
{
vector<int> cplusplus(int n=3,int maximum=1000)
{
int i,j,order,m,i1,i2,mag;
vector<int> output(0);
i=1;
j=0;
while (i/maximum<=1)
{
i=10*i;
j=j+1;
}
m=j-1;
for (i1=1; i1<m+2; i1++)
{
mag=pow(10,(i1-1));
i=0;
while (i+mag*(n+1)<=maximum)
{
for (i2=i+mag*n; i2<i+mag*(n+1); i2++)
{
output.push_back(i2-1);
}
i=i+10*mag;
}
if(i+mag*(n+1)>maximum)
{
for (i2=i+mag*n; i2<maximum+1; i2++)
{
output.push_back(i2-1);
}
}
}
return output;
}
}
I create the .so file using:
g++ -shared -o cplusplus.so cplusplus.cpp
and I call the C++ function in Python using:
import ctypes
cpp=ctypes.cdll.LoadLibrary('/Users/.../cplusplus.so')
print cpp.cplusplus(n=3,maximum=1000)
The function, when returned correctly, should return a vector of all the numbers between 1 and 1000 containing a 3 (i.e. 3,13,23,30,31,...). Currently, however, the Python kernel crashes.
I would imagine it's something to do with my use of vectors or a memory leak in the C++ file.
Thanks in advance for any help!
ctypesnotcpptypes.ctypescan't handle avector<int>. You must have C data types.