【问题标题】:python, C, ctypes and a strange characterpython、C、ctypes 和一个奇怪的字符
【发布时间】:2016-06-14 23:21:55
【问题描述】:

我试图弄清楚如何在python 代码中使用C 函数。看起来到目前为止最简单的解决方案是使用ctypes。但是由于某种原因,在创建导入到 python 的库后,我看到了奇怪的行为。下面提供了所有详细信息。

这是我的C 代码:

/* mymodule.c */
#include <stdio.h>
#include "mymodule.h"
void displayargs(int i, char c, char* s) {
  (void)printf("i = %d, c = %c, s = %s\n", i, c, s);
}

/* mymodule.h */
void displayargs(int i, char c, char* s)

我使用以下命令构建了一个库:

gcc -Wall -fPIC -c mymodule.c
gcc -shared -Wl,-soname,libmymodule.so.1 -o libmymodule.so mymodule.o

我的 Python 测试代码如下所示

#!/usr/bin/python

# mymoduletest.py
import ctypes

mylib = ctypes.CDLL('./libmymodule.so')
mylib.displayargs(10, 'c', "hello world!")

当我运行 ./mymoduletest.py 时,我希望看到

i = 10, c = c, s = hello world!

我怎么看

i = 10, c = �, s = hello world!

为什么显示 字符而不是c 的实际char 值?

感谢任何帮助。

【问题讨论】:

  • Python 有char 类型吗?或者它只是为c传递一个长度为1的字符串?
  • 如果你把它称为mylib.displayargs(10, 99, "hello world!")会发生什么?

标签: python-2.7 ctypes


【解决方案1】:

你需要指定函数的参数和返回类型:

mylib.displayargs.argtypes = (ctypes.c_int, ctypes.c_char, ctypes.c_char_p)
mylib.displayargs.restype = None  # None means void here.

如果你不指定类型,Python 必须猜测,当你传递一个字符串时它做出的猜测是函数想要一个char *

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2011-08-04
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多