出学python,问个导出的小问题

星羽 2011-09-13 08:50:45
cpp的代码



#include "windows.h"
#include "stdio.h"
#include "python.h"

class test
{
public :
test()
: levl(0)
{
(*name) = 0;
}

void setName(const char _name[])
{
memcpy(name, _name, sizeof(name));
}

const char* getName() const
{
return name;
}

void setLevel(int _levl)
{
levl = _levl;
}

int getLevel() const
{
return levl;
}

static void _pyInit(test* self, PyObject* args)
{
(*self->name) = 0;
self->levl = 0;
}

static void _pyDest(test* self)
{
Py_TYPE(self)->tp_free((PyObject*)self);
}

static PyObject* _py_setName(test* self, PyObject* args)
{
Py_INCREF(Py_None);

const char* name = 0;

if (PyArg_ParseTuple(args, "s", &name))
{
strncpy(self->name, name, sizeof(self->name));
}

return Py_None;
}

public :
PyObject_HEAD
char name[128];
int levl;
};

static PyMethodDef _py_test_method[] =
{
{ "setName", (PyCFunction)test::_py_setName, METH_VARARGS, "get name" },
{ NULL, NULL, NULL, NULL }
};

static PyTypeObject _py_test_class =
{
PyVarObject_HEAD_INIT(NULL, 0)
"test",
sizeof(test),
0,
(destructor)test::_pyDest,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
"test class",
0,
0,
0,
0,
0,
0,
_py_test_method,
0,
0,
0,
0,
0,
0,
0,
(initproc)test::_pyInit,
0,
};

static PyModuleDef _py_test_module =
{
PyModuleDef_HEAD_INIT,
"test_module",
"test_module",
-1,
NULL,
NULL,
NULL,
NULL,
NULL
};

int main()
{
Py_Initialize();

if (!Py_IsInitialized())
return 1;

PyObject* module = 0;
_py_test_class.tp_new = PyType_GenericNew;

if (PyType_Ready(&_py_test_class) < 0)
return 1;

module = PyModule_Create(&_py_test_module);

if (!module)
return 1;

Py_INCREF(&_py_test_module);

PyModule_AddObject(module, "test", (PyObject*)&_py_test_class);
PyRun_SimpleString("exec(open('py.py').read())");

Py_Finalize();

return 0;
}



py.py 的代码


import test_module

print(dir())



执行 PyRun_SimpleString("exec(open('py.py').read())");的时候报错了
:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 7, in <module>
ImportError: No module named test_module

找不到模块 - -b


...全文
153 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
完美灬缺陷 2011-09-15
  • 打赏
  • 举报
回复
关注下。
wangjiepro 2011-09-14
  • 打赏
  • 举报
回复
使用boost.python库可以方便地导入导出
iambic 2011-09-14
  • 打赏
  • 举报
回复
http://docs.python.org/extending/embedding.html
可以用PyObject_CallObject调用函数。
CCDDR 2011-09-14
  • 打赏
  • 举报
回复
python只能处理python对象,
如果是从C++传进去的对象,那么这个对象是要定义成PYTHON对象的,比如
PyObject* m_pPythonObject;
m_pPythonObject就可以当成参数传给python去处理
星羽 2011-09-13
  • 打赏
  • 举报
回复
顺便问一下,如果把一个对象做为参数传给python的函数去处理?
星羽 2011-09-13
  • 打赏
  • 举报
回复
自己搞定了 - -b

星羽 2011-09-13
  • 打赏
  • 举报
回复
python的版本是3.2.2

37,718

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧