python利用ctypes库向c的dll库传入字符数组和字符指针
第一类c dll库
生成dll库的头文件
#ifndef _D_TEST_H_
#define _D_TEST_H_
#include <stdio.h>
#include <string.h>
struct person{
char *name;
int weight;
int age;
float height;
};
extern _declspec(dllexport) void add();
extern _declspec(dllexport) void prints(char *s);
extern _declspec(dllexport) void print_info(struct person p1);
#endif
生成dll库的源文件
#include "D_TEST.h"
#include <stdio.h>
void add()
{
printf("%d\n",10);
//return a + b;
}
void prints(char *s)
{
if (s != NULL) printf("%s\n", s);
}
void print_info(struct person p1)
{
//printf("%D\n", strlen(p1.name));
int len = strlen(p1.name);
if (len >= 1) p1.name[0] = '1';
printf("%p %s\n", p1.name, "c");
printf("%d\n", len);
printf("%s c\n", p1.name);
printf("%d\n", p1.weight);
printf("%d\n", p1.age);
printf("%f\n", p1.height);
}
void print_strs(struct person *pers, int n)
{
}
注意
char *name
我们留意到,struct person中的name成员是字符指针,那么对应的python调用代码应该采用如下模式,已经测试过
pdll = cdll.LoadLibrary('plus.dll')
pdll.add()
p = create_string_buffer("Hello", 10)
pdll.prints(p)
class Person(Structure):
_fields_ = [
("name", c_char_p),
("weight", c_int),
("age", c_int),
("height", c_float)
]
p1 = Person()
p1.name = "Hello, World1"
p1.weight = 50
p1.height = 170.0
p1.age = 24
pdll.print_info(p1)
print p1.name + ' ' + "py"
“name”, c_char_p,此处的重点
p1.name = "Hello, World1"也可以改为p1.name = c_char_p(“Hello, World1”)
第二类c dll库
生成dll库的头文件
#ifndef _D_TEST_H_
#define _D_TEST_H_
#include <stdio.h>
#include <string.h>
struct person{
char name[100];
int weight;
int age;
float height;
};
extern _declspec(dllexport) void add();
extern _declspec(dllexport) void prints(char *s);
extern _declspec(dllexport) void print_info(struct person p1);
#endif
生成dll库的源文件
#include "D_TEST.h"
#include <stdio.h>
void add()
{
printf("%d\n",10);
//return a + b;
}
void prints(char *s)
{
if (s != NULL) printf("%s\n", s);
}
void print_info(struct person p1)
{
//printf("%D\n", strlen(p1.name));
int len = strlen(p1.name);
if (len >= 1) p1.name[0] = '1';
printf("%p %s\n", p1.name, "c");
printf("%d\n", len);
printf("%s c\n", p1.name);
printf("%d\n", p1.weight);
printf("%d\n", p1.age);
printf("%f\n", p1.height);
}
void print_strs(struct person *pers, int n)
{
}
注意
char name[100]
我们留意到,struct person中的name成员是字符指针,那么对应的python调用代码应该采用如下模式,已经测试过
pdll = cdll.LoadLibrary('plus.dll')
pdll.add()
p = create_string_buffer("Hello", 10)
pdll.prints(p)
class Person(Structure):
_fields_ = [
("name", c_char * 100),
("weight", c_int),
("age", c_int),
("height", c_float)
]
p1 = Person()
p1.name = "Hello, World1"
p1.weight = 50
p1.height = 170.0
p1.age = 24
pdll.print_info(p1)
print p1.name + ' ' + "py"
“name”, c_char * 100,此处的重点
强调
字符数组对应字符数组,字符指针对应字符指针,一一对应。