gpt4 book ai didi

python - 在 Python 上调用 C 函数只打印第一个字符

转载 作者:行者123 更新时间:2023-12-04 15:08:51 24 4
gpt4 key购买 nike

我尝试在 python 中调用 c 函数,这是我的代码

字符串.c

#include <stdio.h>

int print(const char *str)
{
printf("%s", str):
return 0;
}

字符串.py

from ctypes import *
so_print = "/home/ubuntu/string.so"
my_functions = CDLL(so_print)
print(my_functions.print("hello"))

当我运行 python 脚本时,它只打印字符串的第一个字符例如“h”

我如何传递任何字符串,我的 C 代码将读取并显示它。

最佳答案

您的函数接受 const char*,它对应于 Python bytes 对象(coerces to c_char_p),而不是 str(强制转换为 c_wchar_p)。你没有告诉 Python 底层 C 函数的原型(prototype)是什么,所以它只是将你的 str 转换为 c_wchar_p,并且 UTF-16 或 UTF-32 编码的字符串只有ASCII 字符看起来 像空字符或单个字符(取决于平台字节序)C 风格char * 字符串。

有两点需要改进:

  1. 定义 the prototype for print so Python can warn you when you misuse it, adding :

    my_functions.print.argtypes = [c_char_p]

    在使用该功能之前。

  2. str 参数编码为 bytes,以便它们可以转换为有效的 C 风格 char* 字符串:

    # For arbitrary string, just encode:
    print(my_functions.print(mystr.encode()))

    # For a literal, you can pass a bytes literal
    print(my_functions.print(b"hello"))
    # ^ b makes it a bytes, not str

关于python - 在 Python 上调用 C 函数只打印第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65590561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com