LoginSignup
2
4

More than 3 years have passed since last update.

MacでPythonからC/C++を呼ぶ

Last updated at Posted at 2019-05-30

初投稿です。最近要望があってPython触ってみたけど、遅い。でもPythonで書かなきゃいけないときに「C呼んでしまえばよくね!?」ってなっていろいろ調べてみた。でも他の人が書いた記事の通りにやってもうまくいかなかった。参照か何かが間違ってたのかなぁって感じだったが、強引に動かしたら動いたのでメモ。

概要

Boost.Pythonというやつを使えばいいらしい。ライブラリを参照するのがうまくいかなかったので、一つのディレクトリ内に全部入れて動かした。

環境

macOS 10.13.6
Python 3.7
BoostPython 1.68.0

必要なものを用意する

このプログラムを実行するディレクトリを用意した。どこでもいいと思うが、僕は~/Python/BoostPythonTest/にした。ここに以下のものを用意する。

  • libboost_python37.dylib
  • libpython3.7.dylib
  • C/C++ソース
  • Pythonソース

libboost_python37.dylib

以下でBoost.Pythonをインストールする。1

% brew install boost-python3

インストールしたら/usr/local/Cellar/boost-python3/1.68.0/lib/libboost_python37.dylibがあるはずなので、これを実行するディレクトリにコピーする。

libpython3.7.dylib

Pythonをインストールしておく。1

% brew install python3

/usr/local/Cellar/python/3.7.2/Frameworks/Python.framework/Versions/3.7/Python実行するディレクトリにコピーして、libpython3.7.dylibという名前に変更する。

C/C++ソース

テスト用にhello.cppっていうソースを用意した。

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);
}

Pythonソース

テスト用にtest.pyっていうソースを用意した。

test.py
import hello
x = hello.greet(2)
print(x)
y = hello.file()
print(y)

コンパイル

以下でコンパイルできるはず。実行するディレクトリ内のファイルを参照するだけ。

% g++ -fPIC -Wall -O2 -shared -o hello.so hello.cpp libboost_python37.dylib libpython3.7.dylib

hello.so実行するディレクトリに作られる。

実行

実行してみる。

% python3 test.py
printHELLO!!
3
How are you?

ちゃんとできてそう。

まとめ

一つのディレクトリに全部ぶっ込んで動かすっていうちょっと強引な方法でしたが、とりあえず動いたのでよしとしよう。

Ubuntuでも動かそうとしたけどできなかった。dylib使ってるからMacじゃないとダメみたい。

参考

[1]c/c++をラップしてpythonで使えるように
https://www.quark.kj.yamagata-u.ac.jp/~hiroki/python/?id=19

[2]boost インストールから実行(boost::python)まで。
http://nonbiri-tereka.hatenablog.com/entry/2014/02/01/004547


  1. brewを使うときにパーミッションエラーがでたら、sudo brew ...ってやる。 

2
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4