I wrote the other day
Call the code generated by Cython from C / C ++ (Windows version)
Let's try the Mac version of. It is assumed that Python is using one of the environments in pyenv.
Let's define a vertex structure and create a function that returns a vertex structure with doubled coordinates.
cytest.pyx
cdef public struct Point:
double x
double y
cdef public Point DoubleCoord(Point p):
cdef Point q
q.x=2*p.x
q.y=2*p.y
return q
Also prepare setup.py
.
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("cytest.pyx"))
$ python setup.py build_ext --inplace
By doing this, cytest.h`` cytest.c
should be generated.
Let's write the code as below.
call.c
#include <stdio.h>
#include <Python.h>
#include "cytest.h"
int main(int argc, char const *argv[])
{
Py_Initialize();
struct Point p;
p.x=3.0;
p.y=4.0;
struct Point q = DoubleCoord(p);
printf("Hello\n");
printf("q.x=%f,q.y=%f\n",q.x,q.y);
Py_Finalize();
/* code */
return 0;
}
One thing to note here is that you have to include Python.h
before including cytest.h
.
error: unknown type name 'PyMODINIT_FUNC'
I get angry.
Here, I will try it in the case of 3.5.4 in the pyenv environment.
$ pyenv global
3.5.4
First you have to find out where the Python.h
is.
As conclusion
$HOME/.pyenv/versions/3.5.4/include/python3.5m
Then, if you look at it in Finder, you will see that the header files are lined up.
Rinka looks for the library, so I have to tell her the location. There is lib
in the same hierarchy as ʻinclude`, so let's take a look here.
You found it.
How to use the compiler (gcc command)
Let's write it with reference to.
gcc -Wall -I $HOME/.pyenv/versions/3.5.4/include/python3.5m -L $HOME/.pyenv/versions/3.5.4/lib -lpython3.5m call.c cytest.c
Then the executable file ʻa.out` will be created.
$ ./a.out
Hello
q.x=6.000000,q.y=8.000000
It was confirmed that the vertex coordinates were doubled. Now you can call Python from C / C ++ and vice versa via Cython, so you can work from any direction.
Recommended Posts