Windows使用MSVC,命令行編譯,鏈接64位dll,Python調用


前一篇博客: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

可以看到編譯產生了dllexplibobj四個文件。

鏈接

然後鏈接:

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()

參考:c - What are the exact steps for creating and then linking against a Win32 DLL on the command line? - Stack Overflow

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章