This is the first post. I recently requested to touch Python, but it's slow. But when I had to write it in Python, I asked, "Why don't you call me C !?" But it didn't work as I did in the articles written by others. I was wondering if the reference or something was wrong, but I made a note because it moved when I moved it forcibly.
It seems that you should use the one called ** Boost.Python **. I couldn't browse the library, so I put it all in one directory ** and it worked.
macOS 10.13.6 Python 3.7 BoostPython 1.68.0
I have prepared a directory * to execute this program. I think it can be anywhere, but I chose ~ / Python / BoostPythonTest /
. Prepare the following items here.
libboost_python37.dylib Install Boost.Python below. [^ 1]
% brew install boost-python3
Once installed, you should have /usr/local/Cellar/boost-python3/1.68.0/lib/libboost_python37.dylib
, copy it to the * execute directory *.
libpython3.7.dylib Have Python installed. [^ 1]
% brew install python3
Copy /usr/local/Cellar/python/3.7.2/Frameworks/Python.framework/Versions/3.7/Python
to the * execution directory * and rename it to libpython3.7.dylib
.
I prepared a source called hello.cpp
for testing.
hello.cpp
#include <boost/python.hpp>
#include <stdio.h>
char greet(int x){
printf("printHELLO!!\n");
return '0' + x + 1;
}
char const* fine(){
return "How are you?";
}
BOOST_PYTHON_MODULE(hello){
using namespace boost::python;
def("greet", greet);
def("fine", fine);
}
I prepared a source called test.py
for testing.
test.py
import hello
x = hello.greet(2)
print(x)
y = hello.file()
print(y)
You should be able to compile with: Just browse for the files in * the directory you want to run *.
% g++ -fPIC -Wall -O2 -shared -o hello.so hello.cpp libboost_python37.dylib libpython3.7.dylib
hello.so
is created in the * execution directory *.
Try to run it.
% python3 test.py
printHELLO!!
3
How are you?
It seems to be done properly.
It was a bit of a brute force method to put everything in one directory and move it, but it worked for the time being, so let's do it.
I tried to run it on Ubuntu, but I couldn't. I'm using dylib
, so it seems to be useless unless it's a Mac.
[1] Wrap c / c ++ so that it can be used in python https://www.quark.kj.yamagata-u.ac.jp/~hiroki/python/?id=19
[2] From boost installation to execution (boost :: python). http://nonbiri-tereka.hatenablog.com/entry/2014/02/01/004547
[^ 1]: If you get a permission error when using brew
, dosudo brew ...
.
Recommended Posts