beginner's pyd question - exporting structs to python

Laeeth Isharc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 18 10:17:36 PDT 2014


Thank to jwhear on irc who solved it for me despite claiming not 
to be a pyd guru.

In case it's of benefit, here is what works:

module hellostruct;

import pyd.pyd;
import std.stdio;
import std.conv;

struct t_mystruct {
   int i;
   string s;
};

t_mystruct hellostruct(int[] inp) {
     int i;
     t_mystruct mystruct;

     for (i=0;i<inp.length;i++)
     {
       writefln("inp " ~ to!string(i) ~ " is " ~ 
to!string(inp[i]));
     }
     writefln(" * ok, bye");
     mystruct.i=99;
     mystruct.s="hello there";
     return mystruct;
}

extern(C) void PydMain() {
     def!(hellostruct)();
     module_init();
     wrap_struct!(
       t_mystruct,
       Member!"s",
       Member!"i"
     )();
}

[root at fedora demark]# cat test.py
import os.path, sys
import distutils.util

# Append the directory in which the binaries were placed to 
Python's sys.path,
# then import the D DLL.
libDir = os.path.join('build', 'lib.%s-%s' % (
     distutils.util.get_platform(),
     '.'.join(str(v) for v in sys.version_info[:2])
))
sys.path.append(os.path.abspath(libDir))

import hellostruct
inp=[1,2,3,4]
mystruct= hellostruct.hellostruct(inp)
print mystruct.i
print mystruct.s


More information about the Digitalmars-d-learn mailing list