前一篇博客: Windows下使用Visual Studio自带的MSVC,命令行编译C/C++程序
代码
mylib.h代码如下:
#ifndef MYLIB_H
#define MYLIB_H
#if defined(BUILDING_MYLIB)
#define MYLIB_API __declspec(dllexport) __stdcall
#else
#define MYLIB_API __declspec(dllimport) __stdcall
#endif
#ifdef __cplusplus
extern "C" {
#endif
int MYLIB_API helloworld(void);
#ifdef __cplusplus
}
#endif
#endif
mylib.c代码如下:
#include "mylib.h"
#include <stdio.h>
int MYLIB_API helloworld(void)
{
printf("Hello World DLL");
return 42;
}
main.c 代码如下:
/* No need to include this if you went the module definition
* route, but you will need to add the function prototype.
*/
#include "mylib.h"
int main(void)
{
helloworld();
return (0);
}
编译
打开64位的x64 Nativate Tools Command Prompt for VS 2019
。
先编译dll:
C:\Users\peter>cl /DBUILDING_MYLIB mylib.c /LD
用于 x64 的 Microsoft (R) C/C++ 优化编译器 19.22.27905 版
版权所有(C) Microsoft Corporation。保留所有权利。
mylib.c
Microsoft (R) Incremental Linker Version 14.22.27905.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:mylib.dll
/dll
/implib:mylib.lib
mylib.obj
正在创建库 mylib.lib 和对象 mylib.exp
可以看到编译产生了dll
,exp
,lib
,obj
四个文件。
链接
然后链接:
C:\Users\peter>cl main.c /link mylib.lib
用于 x64 的 Microsoft (R) C/C++ 优化编译器 19.22.27905 版
main.c
/out:main.exe
mylib.lib
main.obj
可以运行了:
C:\Users\peter>main.exe
Hello World DLL
Python调用
Python调用代码如下:
import os
import sys
from ctypes import *
lib = cdll.LoadLibrary('mylib.dll')
# Our 'ctypes' wrapper around the DLL function -- this is where we
# convert Python types to C types and call the DLL function.
def print_helo():
func = lib.helloworld
func()
print_helo()