python - 如何使用 ctypes 在 Python 中发送 char* 类型参数?
问题描述
我在使用 ctypes、Python 库时遇到问题。
我试图在 python 中运行我的 C 代码,但它不起作用。
//this is p.c File
#include <stdio.h>
void printing(char* string){
printf("%s",string);
}
如您所见,这是一个非常简单的代码,它接收带有参数的字符串并打印。
所以我尝试将该文件制作为 DLL,并使用 gcc 64 位版本进行编译。像这样
gcc --shared -op.dll p.o
gcc -fPIC -c p.c
然后,我在 Python 中运行了这段代码
#This is my Python code
from ctypes import *
p = CDLL('./p.dll')
p.printing("help")
在我的运行窗口中,它显示如下。
我以为是 gcc 错误,所以我运行了下一段代码,但这段代码运行良好。
这是我的 C 代码
//this is p.c File
#include <stdio.h>
void printing(char* string){
printf("%s",string);
}
int test(int val){
return val+30;
}
这是我的编译代码。
gcc --shared -op.dll p.o
gcc -fPIC -c p.c
这是我的 Python 代码
#This is my Python code
from ctypes import *
p = CDLL('./p.dll')
print(p.test(123))
如您所见,它显示了 153, 123 + 30 ,这是 test(123) 的结果...
那么我怎样才能打印出我在 C 代码中从 Python 中给出的“你好”呢?
解决方案
好吧,我解决了这个问题。
#This is my Python code
from ctypes import *
args1 = "help"
args1.encode("euc-kr")
p = CDLL('./p.dll')
p.printing.argtypes = [c_char_p]
p.printing(args1)
推荐阅读
- python - 使用鼠标事件绘制模糊矩形
- javascript - Laravel 5.8 中外部 js 文件上的“405 Method not allowed”
- google-cloud-platform - GCP Dataproc 并行步骤执行
- html-email - 阻止 SES 将 awstrack.me 添加到我的所有电子邮件链接
- javascript - 如何访问以下 json 值
- django - Django ORM - 获取具有 OneToOneField 的多个 select_related
- android - 在 Facebook Canvas 上的存在,appwarp android 游戏
- java - BMI 计算器 NaN 输出
- css - Spring MVC,无法加载背景图片
- python - 删除具有相同日期时间的行