1. 程式人生 > >python 呼叫C 常用引數傳遞

python 呼叫C 常用引數傳遞

環境ubuntu 16.04 python3

1.pycall.c

#include <stdio.h>
#include <string.h>
struct test
{
        int key;
        char* val;
};

//傳遞數值
int ValTest(int n)
{
        printf("val:%d\n", n);
        return 0;
}

//傳遞字串
int strTest(char* pVal)
{
        printf("val:%s\n", pVal);
        return 0;
}

//傳遞結構體
int StructTest(struct test data)
{
        printf("key:%d,val:%s\n", data.key, data.val);
        return 0;
}

//傳遞結構體指標
int PointTest(struct test* pData)
{
        printf("key:%d,val:%s\n", pData->key, pData->val);
        return 0;
}

//傳遞陣列
int szTest(int a[], int nLen)
{
        for(int i = 0; i < nLen; i++)
        {
                printf("%d ", a[i]);
        }
        printf("\n");
        return 0;
}
2.pycall.py
# -*- coding: utf8 -*-

import ctypes
from ctypes import *

print ('*' * 20)
print ("傳遞數字")
func = ctypes.cdll.LoadLibrary("./pycall.so")
func.ValTest(2)

print ('*' * 20)
print ("傳遞字串")
val = bytes('qqqqqq',encoding='utf-8')
func.strTest(val)

print ('*' * 20)
print ("傳遞結構體")
class testStruct(Structure):
        _fields_=[('key',c_int),('val',c_char_p)]

s = testStruct()
s.key = 1
s.val = bytes('test',encoding='utf-8');
func.StructTest(s)

print ('*' * 20)
print ("傳遞結構體指標")
func.PointTest(byref(s))

print ('*' * 20)
print ("傳遞陣列")
INPUT = c_int * 10
data = INPUT()
for i in range(10):
        data[i] = i

func.szTest(data,len(data))
print ('*' * 20)
3.makefile
#COMPLILER USED
CC = gcc
AR = ar cru

#SO FLAG
 SHARE = -shared -fPIC

 TARGET = pycall

#EXE PGM  AND LIB
 all: ${TARGET}

#MAKE RULE
 ${TARGET}:
        $(CC) [email protected] $(SHARE) $^ -o [email protected]

 clean:
        rm -f ${TARGET}.so
4.結果