windows - 如何在 Windows 上编译共享库,使其可以与 raku 中的 NativeCall 一起使用?
问题描述
我正在尝试在 Windows 上编译一个可以与Raku 中的NativeCall一起使用的 DLL 库。这是一个最小的 C 代码 ( my_c_dll.c
):
#include <stdio.h>
#define EXPORTED __declspec(dllexport)
extern __declspec(dllexport) void foo();
void foo()
{
printf("Hello from C\n");
}
我在 Windows 10 上并已安装Build Tools for Visual Studio 2019。要编译 DLL,我打开“VS 2019 的开发人员命令提示符”并运行:
> cl.exe /c my_c_dll.c
> link /DLL /OUT:my_c_dll.dll my_c_dll.obj
这将创建一个 DLL my_c_dll.dll
,然后我尝试从 Raku ( test-dll.raku
) 使用它:
use v6.d;
use NativeCall;
sub foo() is native("./my_c_dll.dll"){ * }
foo();
但是当我运行它时(我已经安装了 Rakudo 版本 2020.05.1),我得到:
> raku test-dll.raku
Cannot locate native library '(null)': error 0xc1
in method setup at C:\rakudo\share\perl6\core\sources\947BDAB9F96E0E5FCCB383124F923A6BF6F8D76B (NativeCall) line 298
in block foo at C:\rakudo\share\perl6\core\sources\947BDAB9F96E0E5FCCB383124F923A6BF6F8D76B (NativeCall) line 594
in block <unit> at test-dll.raku line 9
这里有什么问题?
解决方案
找不到本机库“(空)”:错误 0xc1
错误代码0xc1
是Windows 系统错误代码:
ERROR_BAD_EXE_FORMAT
193 (0xC1)
%1 is not a valid Win32 application.
> dumpbin /headers my_c_dll.dll
Microsoft (R) COFF/PE Dumper Version 14.26.28806.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file my_c_dll.dll
PE signature found
File Type: DLL
FILE HEADER VALUES
14C machine (x86)
4 number of sections
6043A8CB time date stamp Sat Mar 6 17:07:39 2021
0 file pointer to symbol table
0 number of symbols
E0 size of optional header
2102 characteristics
Executable
32 bit word machine
DLL
我观察到它说machine (x86)
and 32 bit word machine
,所以我怀疑 DLL 是 32 位 DLL。但是,我在 64 位机器上:
> PowerShell -Command "systeminfo | perl -nE 'say if /System Type/'"
System Type: x64-based PC
事实证明,Build Tools for Visual Studio 2019
除了“VS 2019 的开发者命令提示符”之外,还安装了一些开发者提示符,即:
- VS 2019 的 x64 本机工具命令提示符
- VS 2019 的 x64_x86 交叉工具命令提示符
- VS 2019 的 x86 本机工具命令提示符
- VS 2019 的 x86_x64 交叉工具命令提示符
通过打开“x64 Native Tools Command Prompt for VS 2019”并在此处重新编译 DLL,我现在得到:
> dumpbin /headers my_c_dll.dll
Microsoft (R) COFF/PE Dumper Version 14.26.28806.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file my_c_dll.dll
PE signature found
File Type: DLL
FILE HEADER VALUES
8664 machine (x64)
6 number of sections
6043AAA2 time date stamp Sat Mar 6 17:15:30 2021
0 file pointer to symbol table
0 number of symbols
F0 size of optional header
2022 characteristics
Executable
Application can handle large (>2GB) addresses
DLL
请注意,输出现在显示machine (x64)
and Application can handle large (>2GB) addresses
,这似乎也解决了问题:
> raku test-dll.raku
Hello from C
推荐阅读
- vue.js - Webpack 配置间歇性工作
- wordpress - 如何删除 /sub1/ 并将此子文件夹中的所有 wordpress 定向到根目录?
- html - 如何修复警告“表格行宽 2 列,超过了第一行 (1) 建立的列数。”
- r - var.test 的问题
- c++ - 使用 CMake 以 C++/WinRT 为目标
- php - 如何将多维键值转换为单个数组?
- c# - C# db 示例代码抛出“连接属性尚未初始化”
- android - 搜索栏垂直但布局仍然是水平的
- android-fragments - 如何使用相同的按钮添加和删除片段
- java - Spring boot resttemplate 获取请求发现 401 未授权异常