首页 > 解决方案 > 如何使用 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 中给出的“你好”呢?

标签: pythoncpython-3.xctypes

解决方案


好吧,我解决了这个问题。


#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)


推荐阅读