❶ 如何在python中調用c語言代碼
先把C語言代碼做成DLL文件,再用python載入此DLL文件來訪問C語言功能代碼
❷ python 怎麼調用c語言介面
ctypes: 可直接調用c語言動態鏈接庫。
使用步驟:
1> 編譯好自己的動態連接庫
2> 利用ctypes載入動態連接庫
3> 用ctype調用C函數介面時,需要將python變數類型做轉換後才能作為函數參數,轉換原則見下圖:
#Step1:test.c#include<stdio.h>
intadd(inta,intb)
{
returna+b;
}#Step2:編譯動態鏈接庫(如何編譯動態鏈接庫在本文不詳解,網上資料一大堆。)gcc-fPIC-sharedtest.c-olibtest.so
#Step3:test.py
fromctypesimport*mylib=CDLL("libtest.so")或者cdll.LoadLibrary("libtest.so")add=mylib.add
add.argtypes=[c_int,c_int]#參數類型,兩個int(c_int是ctypes類型,見上表)
add.restype=c_int#返回值類型,int(c_int是ctypes類型,見上表)
sum=add(3,6)
❸ Python 有沒有和 C/C++ 進程共享內存的方式
通過share memory 取對象的例子, c write object into memory map, python read it by call dll api.
So there still questions you should consider how to guarantee the process share security. Good luck..
----python part----
from ctypes import *
#windll.kernel32.SetLastError(-100)
print windll.kernel32.GetLastError()
getMessage=windll.kernel32.OpenFileMappingA
getMessage.restype = c_int
handle=getMessage(1,False,"Global\\MyFileMappingObject")
if handle ==0:
print 'open file mapping handle is Null'
else:
mapView=windll.kernel32.MapViewOfFile
mapView.restype = c_char_p
print mapView(handle,1,0,0,256)
----c part----
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[] = TEXT("Message from first process.");
int _tmain()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return 1;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
❹ 如何利用python實現類似c語言的共同體
import ctypes #你可以看看ctypes,它可以支持union,下面是一個例子
from ctypes import ( Union, Array,
c_uint8, c_uint32,
cdll, CDLL
)
class uint8_array(Array):
_type_ = c_uint8
_length_ = 4
class u_type(Union):
_fields_ = ("data", c_uint32), ("chunk", uint8_array)
# load printf function from Dynamic Linked Libary libc.so.6 (I'm use linux)
libc = CDLL(cdll.LoadLibrary('libc.so.6')._name)
printf = libc.printf
if __name__ == "__main__": # initialize union
_32bitsdata = u_type() # set values to chunk
_32bitsdata.chunk[:] = (1, 2, 3, 4) # and print it
printf(b"Data in 32 bits: %d\n", _32bitsdata.data)