嵌入Python
我试图从 C 代码调用 python 函数,并且我遵循了 这里
我也有正确的包含文件目录、库目录,并链接了python32.lib(我使用python 32),但是错误是python/C API,例如PyString_FromString、PyInt_FromLong, PyInt_AsLong 未定义(调试器中的错误)
这很奇怪,因为我也使用其他 API,但它们都很好......
这里有什么问题?
int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
Py_Initialize();
pName = PyString_FromString(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pDict = PyModule_GetDict(pModule);
/* pDict is a borrowed reference */
Py_Initialize()、PyImport_Import()、PyModule_GetDict() 都可以正常工作,但 PyString_FromString 不行...
Im trying to call python functions from C code, and i followed a sample from here
I also have the correct include file directries, library directries, and linked the python32.lib (im using python 32) however the error was that python/C APIs such as PyString_FromString, PyInt_FromLong, PyInt_AsLong are undefined (error in the debugger)
this is strange because im also using other APIs, but they're all fine...
whats the problem here??
int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
Py_Initialize();
pName = PyString_FromString(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pDict = PyModule_GetDict(pModule);
/* pDict is a borrowed reference */
Py_Initialize(), PyImport_Import(), PyModule_GetDict() all work fine, but not PyString_FromString...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用的示例代码适用于古老的 Python 版本 2.3.2。 Python 3.x 系列不仅在语言中引入了许多不兼容性,在 C API 中也引入了许多不兼容性。
你提到的函数在 Python 3.2 中已经不存在了。
PyString_
函数已重命名为PyBytes_
。PyInt_
函数已消失,应使用PyLong_
代替。下面是您使用的相同示例,但适用于 Python 3:
5.3。纯嵌入
请注意,它使用
PyUnicode_
而不是PyString_/PyBytes_
。在 Python 2.x 使用字节字符串的许多地方,Python 3.x 使用 unicode 字符串。顺便说一句,我通常使用此页面来查找所有可能的调用:
Index – P
The example code you used is for ancient Python version, 2.3.2. Python 3.x line introduced a number of incompatibilites not only in the language but in the C API as well.
The functions you mention simply no longer exist in Python 3.2.
PyString_
functions were renamed toPyBytes_
.PyInt_
functions are gone,PyLong_
should be used instead.Here's the same example that you've used but for Python 3:
5.3. Pure Embedding
Note that it's using
PyUnicode_
instead ofPyString_/PyBytes_
. In many places where Python 2.x used byte strings, Python 3.x uses unicode strings.By the way, I usually use this page to look up all possible calls:
Index – P