fc2ブログ
PyCXXの簡単な例
MacOSX10.5のPython2.6で動かせる簡単なPyCXXの例を、貼り付けておきます。

test.cxx

#ifdef _MSC_VER
// disable warning C4786: symbol greater than 255 character,
// nessesary to ignore as <map> causes lots of warning
#pragma warning(disable: 4786)
#endif

#include "CXX/Objects.hxx"
#include "CXX/Extensions.hxx"

class test_module : public Py::ExtensionModule<test_module>{
public:
test_module():Py::ExtensionModule<test_module>( "test" ){
add_varargs_method("func", &test_module::func2, "test function2");
initialize( "this is the test module" );
}

virtual ~test_module()
{}

private:

Py::Object func2 (const Py::Tuple &args){
Py::List res = args[0];
res.append(Py::Float(args[1]));
std::cout << res[-1] << std::endl;
return res;
}

};

extern "C" void inittest()
{
#if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL)
Py::InitialisePythonIndirectPy::Interface();
#endif

static test_module* test = new test_module;
}

// symbol required for the debug version
extern "C" void inittest_d()
{ inittest(); }


mac_py26.mak

#
# Build the example on Mac OS X for version 2.6
#
CC=gcc -arch i386
CCC=g++ -arch i386
CCCFLAGS=-c -g -fPIC -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I.
LDSHARED=$(CCC) -bundle -g -u _PyMac_Error -F/Library/Frameworks -framework System \
/Library/Frameworks/Python.framework/Versions/2.6/Python
LDLIBS=
PYTHON=/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python

COMMON_OBJECTS=cxxsupport.o cxx_extensions.o cxxextensions.o IndirectPythonInterface.o
MY_OBJECTS=test.o

all: test.so

#
# my object
#
test.so: $(MY_OBJECTS) $(COMMON_OBJECTS)
$(LDSHARED) -o $@ $(MY_OBJECTS) $(COMMON_OBJECTS) $(LDLIBS)

test.o: test.cxx
$(CCC) $(CCCFLAGS) -o $@ $<

#
# common objects
#
cxxsupport.o: Src/cxxsupport.cxx
$(CCC) $(CCCFLAGS) -o $@ $<

cxx_extensions.o: Src/cxx_extensions.cxx
$(CCC) $(CCCFLAGS) -o $@ $<

cxxextensions.o: Src/cxxextensions.c
$(CC) -c $(CCCFLAGS) -o $@ $<

IndirectPythonInterface.o: Src/IndirectPythonInterface.cxx
$(CCC) $(CCCFLAGS) -o $@ $<

#
# Clean rule
#
clean:
rm -f *.o
rm -f test.so

どちらも、サンプルファイルをちょっと変更してわかりやすくしただけですが、これだけで結構Py::Listの動きなどよくわかると思います。

~/pycxx-6.1.1$ make -f mac_py26.mak

で、test.soができていることを確認して、インタラクティブシェルを起動します。

~/pycxx-6.1.1$ python
Python 2.6.3 (r263:75184, Oct  2 2009, 07:56:03)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import test
>>> l = test.func(range(3),10)
10.0
>>> l
[0, 1, 2, 10.0]
>>> type(l)
<type 'list'>
>>>

という具合に使えます。
C++でコードを書くとき、ラッパーオブジェクトをどのあたりまで使ったらいいのかとか、本格的なプログラミングには、すこし考えが必要ですかね。
スポンサーサイト



テーマ:プログラミング - ジャンル:コンピュータ

【2009/10/27 17:58】 | Python | トラックバック(0) | コメント(0) | page top↑
<<MacOSXのインテルコンパイラでOpenMP | ホーム | C++でPythonを拡張したい!>>
コメント
コメントの投稿














管理者にだけ表示を許可する

トラックバック
トラックバックURL
→http://tanopy.blog79.fc2.com/tb.php/42-5b5f9843
この記事にトラックバックする(FC2ブログユーザー)
| ホーム |