python - 预期字节或整数地址而不是 str 实例 Python 3

标签 python c++ ctypes

<分区>

fib.cpp

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
using namespace std;

extern "C" const char *hello (char* b){
static string s = "hello ";
s = s + b;
return s.c_str();
}

wrap.py

import ctypes
_libfib = ctypes.CDLL('./fib.so');

def ctypes_hello(a):
    _libfib.hello.restype = ctypes.c_char_p;
    return _libfib.hello(ctypes.c_char_p(a));

Generate .so files

g++ -std=c++11 -shared -c -fPIC fib.cpp -o fib.o
g++ -std=c++11 -shared -Wl,-soname,fib.so -o fib.so fib.o

从命令行运行 wrap.py

from wrap import *
ctypes_hello("world")

Its working perfectly with python 2. I am getting Error bytes or integer address expected instead of str instance when I switch to Python 3

最佳答案

Python 3 区分字节字符串和 unicode 字符串。所以在 Python 3 中你的“world”字符串是一个 Unicode 代码点序列,而不是一个简单的字节串。所以在 Python 3 中尝试:

ctypes_hello(b"world")

将字节串传递给函数。

关于python - 预期字节或整数地址而不是 str 实例 Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47575449/

相关文章:

python - 当文件不存在时忽略 ftplib 的 550 错误并继续处理其他文件

python - 没有列表理解的具有二维权重数组的 4D 数组的 Numpy 加权平均值

python - 通过 Windows 上的 ctypes 将文件描述符传递给 C 库函数

python - 在 python 中使用 ctypes 从 .so 文件链接时出现奇怪的改变行为

python - 你如何确定 Python 中的处理时间?

python : Compare two large files

c++ - opencv内存位置异常

c++ - 不需要时静态初始化

c++ - 如何在 C++ 中识别在 linux 世界中按下的 shift/ctrl 键(不使用 GL 和 X11/XKBlib.h)?

python - 在Python模块中调用C头文件函数