0
点赞
收藏
分享

微信扫一扫

Python&C++相互混合调用编程全面实战-05ctypes给c函数传递char字符串和wchar_t宽)

兮城 2022-08-15 阅读 113


作者:虚坏叔叔

早餐店不会开到晚上,想吃的人早就来了!😄

ctypes给c函数传递char字符串和wchar_t宽)

一、api介绍

​Python​​​有2种字符串 ​​string​​​ 和 ​​byte​​。

byte对应的是普通char*,是ascii存放。分别通过​​c_whar_p()​​​ 以及 ​​c_char_p()​​ 存放。

​creat_string_buffer()​

​string​​​ 和 ​​byte​​​都是只读类型 要想在c语言中可以修改,就必须调用​​creat_string_buffer()​

二、实战参数传递

C++接收传递过来的字符串

// C++ 中编译c格式的函数,如果用c语言编译就不需要(文件后缀名.c)
// __declspec(dllexport)函数导出到库中
#include <stdio.h>

#ifdef __cplusplus
#define XEXT extern "C"
#else
#define XEXT
#endif

#ifdef _WIN32
#define XLIB XEXT __declspec(dllexport)
#else
#define XLIB XEXT
#endif

// c_char_p
XLIB void TestStringA(const char *str, int size) {
printf("TestStringA : %s (%d)\n", str, size);
}

// c_wchar_p
XLIB void TestStringW(const wchar_t *str, int size) {
printf("TestStringW : %ls (%d)\n", str, size);
}

XLIB void TestCtyps(int x, float y, bool isNum)
{
printf("In C TestCtypes %d %f %d\n", x, y, isNum);
if (isNum)
{
printf("true");
}
else
{
printf("false");
}
}

python中调用

print("Test Ctypes")
from ctypes import *

#导入库 windows中dll后缀名不用加
lib = CDLL("C:\\Users\\Administrator\\Desktop\\testctypes\\x64\\Debug\\testctypes")

try:
str1 = b"test string in python"
lib.TestStringA(str1, len(str1))

wstr = "wide string in python"
lib.TestStringW(wstr, len(wstr))
except Exception as ex:
print("testCtypes Error", ex)
# 等待用户输入,程序不退出
input()

运行结果:

Python&C++相互混合调用编程全面实战-05ctypes给c函数传递char字符串和wchar_t宽)_c++

三、总结

  • 本文主要介绍ctypes给c函数传递char字符串和wchar_t宽)。



举报

相关推荐

c语言 宽字符 wchar_t

0 条评论