当前位置:首页 » 编程语言 » python获取c语言共享内存
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

python获取c语言共享内存

发布时间: 2022-08-08 22:05:08

❶ 如何在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)