python中使用動態庫

來源:互聯網
上載者:User

首先,建立一個簡單的動態庫
編程產生dll.so:   gcc -fPIC -O2 -shared dll.c -o dll.so
C檔案:dll.c  如下

#include <stdio.h>

struct param {
int a;
int b;
char c;
float f;
int arr[3];
};

void print0(struct param arg)
{
printf("in print:\n");
printf("a: %d\n", arg.a);
printf("b: %d\n", arg.b);
printf("c: %c\n", arg.c);
printf("f: %f\n", arg.f);
printf("arr: %d %d %d\n", arg.arr[0], arg.arr[1], arg.arr[2]);
}

void print2(struct param *arg)
{
printf("in print2 :\n");
printf("a: %d\n", arg->a);
printf("b: %d\n", arg->b);
printf("c: %c\n", arg->c);
printf("f: %f\n", arg->f);
printf("arr: %d %d %d\n", arg->arr[0], arg->arr[1], arg->arr[2]);
}

void print3(int a)
{
printf("in print3:\n");
printf("a: %d\n", a);
}

python定義傳給動態庫的結構體

from ctypes import *

class ss(Structure):
_fields_ = [
("a", c_int),
("b", c_int),
("c", c_char),
("f", c_float),
    ("arr", c_int*3),  //定義數組
]

python 使用dll.so執行個體

#載入動態庫
fileName = "/home/primax/Desktop/Work/Test/python/dll.so"
lib = cdll.LoadLibrary(fileName)
#定義變數
param = ss()
#給結構體賦值
param.a = 1
param.b = 2
param.c = 'a'
param.f = 1.2345
param.arr[0] = 0
param.arr[1] = 1
param.arr[2] = 2

lib.print0(param)
lib.print3(2)
#傳指標 pointer取指標
lib.print2(pointer(param))
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.