4

我正在尝试在 Mac 中编译一个简单的 C 扩展以与 Python 一起使用,并且在命令行中一切正常。下面介绍了有效的代码和 gcc 命令。现在我正在尝试在 Xcode 4.5 (Mac OS10.8) 中构建相同的扩展,并且我尝试了 dylib 或静态库的几个目标设置,但我总是得到一个无法在 Python 中加载的文件,显示错误:

./myModule.so: unknown file type, first eight bytes: 0x21 0x3C 0x61 0x72 0x63 0x68 0x3E 0x0A

我的最终目标是在 XCode 中使用 C/C++ 扩展的源代码创建一个工作区,并拥有在 Xcode 中调用它的 python 脚本。所以,如果我需要调试 C/C++ 扩展,我有 XCode 调试功能。我知道 XCode 不会调试到 Python 脚本,但它可以运行它,对吗?

gcc -shared -arch i386 -arch x86_64 -L/usr/lib/python2.7 -framework python -I/usr/include/python2.7 -o myModule.so myModule.c -v

#include <Python.h>

/*
 * Function to be called from Python
 */
static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
    char *s = "Hello from C!";
    return Py_BuildValue("s", s);
}   

/*
 * Another function to be called from Python
 */
static PyObject* py_myOtherFunction(PyObject* self, PyObject* args)
{
    double x, y;
    PyArg_ParseTuple(args, "dd", &x, &y);
    return Py_BuildValue("d", x*y);
}

/*
 * Bind Python function names to our C functions
 */
static PyMethodDef myModule_methods[] = {
    {"myFunction", py_myFunction, METH_VARARGS},
    {"myOtherFunction", py_myOtherFunction, METH_VARARGS},
    {NULL, NULL}
};

/*
 * Python calls this to let us initialize our module
 */
void initmyModule()
{
    (void) Py_InitModule("myModule", myModule_methods);
}
4

2 回答 2

4

这家伙似乎也有同样的问题

我已经弄清楚了问题所在。即使我更改了 xcode 中的设置以指定输出类型“动态库”或“捆绑”,xcode 也忽略了该设置。启动一个新的 BSD 动态库项目解决了我看到的问题。谢谢您的帮助!

于 2012-11-10T19:32:12.897 回答
1

I've had success debugging unit-tested C extensions in XCode 4.6 using setuptools, virtualenv, unittest and GDB as the debugger.

I use virtualenvwrapper to create a virtualenv for the project and then set ~/.virtualenvs/module_name/bin/python as the executable to debug.

The single argument to pass to the virtualenv python interpreter in the Run configuration is the path to your test.py.

I then set GDB rather than None as the debugger launching it automatically.

The last step is to pass "setup.py install" as the arguments to your build tool (~/.virtualenvs/module_name/bin/python) on your test target's External Build Tool Configuration pane. The virtualenv provides a fairly simple way for you to install the shared object for your C extension into the test script python interpreter's library path without actually installing it into the global site-packages for your host.

With this setup I can call the extension code from a python script (the ultimate aim) and still debug the C code using XCode's GUI debug support.

If I haven't described this clearly please let me know and I'll share an example project.

于 2013-04-06T07:08:18.527 回答