2012-11-10 42 views
3

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

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

我最终的目标是在XCode中用C/C++扩展的源代码创建一个工作空间,并使用python脚本在Xcode中调用它。所以,如果我需要调试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); 
} 
+0

前8个字节解码为“! \ n”。这对你来说意味着什么? –

回答

3

This guy seems to be having the same problem

I've figured out the problem. Even though I changed the setting in xcode to specify output type "dynamic library" or "bundle", xcode was ignoring the setting. Starting a new BSD dynamic library project solved the issues I was seeing. Thanks for the help!

0

我使用setuptools的,的virtualenv,单元测试和GDB作为调试器有XCode中4.6成功调试单元测试C扩展。

我使用virtualenvwrapper为项目创建virtualenv,然后将〜/ .virtualenvs/module_name/bin/python设置为要调试的可执行文件。

在运行配置中传递给virtualenv python解释器的单个参数是test.py的路径。

然后我设置GDB而不是None作为调试器自动启动它。

最后一步是在测试目标的“外部构建工具配置”窗格上将“setup.py install”作为参数传递给构建工具(〜/ .virtualenvs/module_name/bin/python)。 virtualenv为您提供了一种非常简单的方法,可以将C扩展的共享对象安装到测试脚本python解释器的库路径中,而无需将其实际安装到您的主机的全局站点包中。

使用此设置,我可以从python脚本(最终目标)调用扩展代码,并仍然使用XCode的GUI调试支持来调试C代码。

如果我没有描述清楚,请让我知道,我会分享一个示例项目。

+0

作为奖励,我可以在IntelliJ/IDEA(PyCharm)中调试Python测试的一面,同时将Xcode中的GDB调试器附加到测试运行器进程中,以便在Xcode中同时调试C扩展端。 – Dave