我最近在尝试使用swig生成一个c语言项目的python接口,但是碰到一些指针传递的问题。以下是我的代码:
// swig_test.c
POINT *test() {
POINT point;
point.x = 5;
point.y = 2;
//int r = point.x%point.y;
printf("test\n");
printf("point.x: %d, %d\n", point.x, &(point.x));
printf("point.y: %d\n", point.y);
printf("&point: %d\n\n", &point);
return &point;
}
int test2(POINT *p)
{
POINT point = *p;
printf("p: %d, %d, %d\n", p, (*p).x, (*p).y);
printf("test2\n");
printf("point.x: %d, %d\n", (*p).x, point.x);
printf("point.y: %d, %d\n", (*p).y, point.y);
printf("point.x: %d\n", point.x);
printf("point.y: %d\n", point.y);
int r = 1; //point.x% point.y;
return r;
}
int main()
{
POINT *p = test();
int r = test2(p);
printf("%d", r);
}
// swig_test.h
#include <stdio.h>
#include <string.h>
struct POINT;
typedef struct POINT POINT;
struct POINT
{
unsigned int x;
unsigned int y;
};
POINT *test();
int test2(POINT *p);
// swig_test.i
%module swig_test
%{
/* Put header files here or function declarations like below */
#include "swig_test.h"
extern POINT *test();
extern int test2(POINT *p);
%}
%include "swig_test.h"
extern POINT* test();
extern int test2(POINT* p);
// main.py
import _swig_test as module
global point
point = module.test()
print(module.test2(point))
当我只运行C的可执行文件版本时,输出是正确的:
test
point.x: 5, 2012281584
point.y: 2
&point: 2012281584
p: 2012281584, 5, 2
test2
point.x: 2012274424, 5
point.y: 0, 2
point.x: 5
point.y: 2
1
但是当我生成了pyd动态库并链接进python,指针传递进test2后所指向的值就发生了变化:
test
point.x: 5, 666825456
point.y: 2
&point: 666825456
p: 666825456, 666825496, 119
test2
point.x: 666825496, 666825496
point.y: 119, 119
point.x: 666825496
point.y: 119
1
由命令行可见,被传递的指针本身没有变化,但是所指向的值变了,请问这是为什么?难道python在结束test之后,所有变量已经都被释放了?