Dear all,
PythonEngine.Initialize();
// create __main__ and my own module
PyModule __main__ = new PyModule(PythonEngine.ImportModule("__main__"));
PyModule birdwrapper = new PyModule(PythonEngine.ImportModule("birdwrapper"));
// set the value of the attribute to a managed object
birdwrapper.SetAttr("pet", PyObject.FromManagedObject(new Eagle("Foo")));
// include my own module in the __main__ module
__main__.AddObject("birdwrapper", birdwrapper);
// run the script from this method because it is called from the __main__ module
PythonEngine.RunSimpleString("birdwrapper.Fly()");
PythonEngine.Shutdown();
internal static bool PyModule_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == Runtime.PyModuleType;
}
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
ExactSpelling = true, CharSet = CharSet.Ansi)]
internal unsafe static extern int
PyModule_AddObject(IntPtr module, string name, IntPtr value);
public class PyModule : PyObject
{
public PyModule(IntPtr ptr) : base(ptr) { }
public PyModule(PyObject o) : base()
{
if (!IsModuleType(o))
{
throw new ArgumentException("object is not a module");
}
Runtime.Incref(o.obj);
obj = o.obj;
}
public PyModule(string name) : base()
{
obj = Runtime.PyModule_New(name);
if (obj == IntPtr.Zero)
{
throw new PythonException();
}
}
public static bool IsModuleType(PyObject value)
{
return Runtime.PyModule_Check(value.obj);
}
public void AddObject(string name, PyObject value)
{
int op = Runtime.PyModule_AddObject(obj, name, value.obj);
if (op != 0)
throw new PythonException();
}
}