{ "name": "pydtest", "targetType": "executable", "dependencies": { "pyd": "~>0.9.7" }, "subConfigurations": { "pyd": "python34" } }
import std.stdio; import pyd.pyd, pyd.embedded; void main() { py_init(); auto script = new InterpContext; // 2 // myscript.py script.py_stmts( "import sys" ); script.py_stmts( "sys.path.append('.')" ); script.py_stmts( "import myscript" ); writeln( script.py_eval!string( "myscript.func()" ) ~ " from pyd" ); }
def func(): return "hello habr!"
dub build && ./pydtest
hello habr! from pyd
def sum(a,b): return a + b
... script.x = 13; script.y = 21; writefln( "result: %d", script.py_eval!int( "myscript.sum(x,y)" ) ); ...
@property PydObject opDispatch(string id)() { // return this.locals[id]; } @property void opDispatch(string id, T)(T t) { // static if(is(T == PydObject)) { alias ts; }else{ PydObject s = py(t); } this.locals[id] = py(s); }
... script.py_stmts( "z = myscript.sum(8,7)" ); writefln( "result2: %d", script.z.to_d!int ); ...
... auto sum = script.myscript.sum; writefln( "result3: %d", sum(14,15).to_d!int ); ...
script.myscript.sum(14,15).to_d!int; // , , script.myscript.oneargfunc(12).to_d!int; // , oneargfunc(12) opDispatch 12 script.myscript.oneargfunc()(12).to_d!int; // : oneargfunc(), opCall(12)
module dcode; import pyd.pyd; import std.math; float[] calc( float x, float y ) { return [ sqrt(x*y), x^^y, x/y ]; } extern(C) void PydMain() { def!(calc)(); module_init(); }
from pyd.support import setup, Extension projName = 'dcode' setup( name=projName, version='0.1', ext_modules=[ Extension(projName, ['dcode.d'], extra_compile_args=['-w'], build_deimos=True, d_lump=True ) ], )
python3 setup_my_dcode.py build
build βββ lib.linux-x86_64-3.4 β βββ dcode.cpython-34m.so βββ temp.linux-x86_64-3.4 βββ infra βββ pydmain.d βββ so_ctor.o βββ temp.o
python3 Python 3.4.1 (default, Nov 3 2014, 14:38:10) [GCC 4.9.1 20140930 (Red Hat 4.9.1-11)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import dcode >>> dcode.calc( 5, 12 ) [7.745966911315918, 244140624.0, 0.4166666567325592] >>>
class Foo { float a = 0, b = 0; static string desc() { return "some ops"; } this( float A, float B ) { a = A; b = B; } float sum() const { return a + b; } float div() const { return a / b; } } extern(C) void PydMain() { def!(calc)(); // module_init(); // wrap_class!( // Foo, Init!(float,float), Repr!(Foo.toString), // python Def!(Foo.sum), Def!(Foo.div), StaticDef!(Foo.desc) )(); }
python3 Python 3.4.1 (default, Nov 3 2014, 14:38:10) [GCC 4.9.1 20140930 (Red Hat 4.9.1-11)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from dcode import Foo >>> Foo.desc() 'some ops' >>> a = Foo(1,2) >>> a.div() 0.5 >>> a.sum() 3.0 >>>
Source: https://habr.com/ru/post/259727/
All Articles