其他高级语言与c通过dll混合编程的一种实现方法

Posted by Mr.Zhang on 2023-06-11
Estimated Reading Time 1 Minutes
Words 332 In Total

此篇博文最早发表于博客园,种种原因,早已不在那边更新了,但此篇有一定价值,遂迁移至此。

工作需要做某平台产品上位机时,由于系列化原因,部分算法需要根据不同产品系列进行微调,为方便后期可可扩展性,遂将相关算法通过LabVIEW读取配置文件调用dll实现。故在此将实现方法记录备用。

记录工作中遇到的一些语言之间交互的方法

开发环境:

gcc version 8.1.0 (x86_64-win32-sjlj-rev0, Built by MinGW-W64 project)

labview 32bit

python 3.11.3

c语言实现dll库:

参考 https://www.cnblogs.com/ser0632/p/4920653.html

创建dllTest.c文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include "stdint.h"
#include "stdio.h"
#include "dllTest.h"

EXPORT void say_hello()
{
printf("Hello, from TestDll!\n");
}

EXPORT uint32_t test_add(uint32_t a, uint32_t b)
{
return a + b;
}

创建dllTest.h文件:

1
2
3
4
5
6
7
8
9
10
#include "stdint.h"

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

EXPORT void say_hello();
EXPORT uint32_t test_add(uint32_t a, uint32_t b);

gcc编译为32bit dll库命令:

1
gcc -m32 -shared -o dllTest.dll dllTest.c

LabVIEW调用dll方法:

调用

运行结果

结果

Python调用dll方法:

1
2
3
4
5
6
7
8
9
import ctypes

test_add = ctypes.CDLL("./dllTest.dll").test_add

# 用ctypes 数据类型,定义函数的参数类与返回值类型
test_add.argtypes = [ctypes.c_uint32,ctypes.c_uint32]
test_add.restype = ctypes.c_uint32

print(test_add(3,5))

运行结果

结果


如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !