在 Xcode for Mac 中编译和链接 Python 的 C 扩展 [英] Compiling and linking C extension for Python in Xcode for Mac

查看:51
本文介绍了在 Xcode for Mac 中编译和链接 Python 的 C 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to compile a simple C extension in Mac to use with Python, and all works well in the command line. Code and gcc command that works are presented below. Now I am trying to build the same extension in Xcode 4.5 (Mac OS10.8), and I tried several target settings for either dylib or static library, but I always get a file that cannot be loaded in Python showing the error:

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

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

My ultimate target is to create a workspace in XCode with the source code of a C/C++ extension and have python script that calls it in Xcode. So, if I need to debug the C/C++ extension I have XCode debugging capabilities. I am aware that XCode do not debug into Python script, but it can run it, correct ?

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);
}

推荐答案

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

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

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!

这篇关于在 Xcode for Mac 中编译和链接 Python 的 C 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆