gpt4 book ai didi

c - D与C库集成导致输出乱码

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:12 25 4
gpt4 key购买 nike

我有一个 C 库,其中包含如下内容:

Abc.h文件

typedef struct
{
uint8_t dbtype;
uint32_t dbcount;
} Abc;

void test_string(Abc* abcobj, char* strA, char* strB);
Abc* create_abc(void);

Abc.c

void test_string(Abc* abcobj, char* strA, char* strB)
{
printf("Str A is %s and str B is %s\n", strA, strB);
return;
}

Abc* create_abc()
{
Abc* abcobj;
abcobj = (Abc*) calloc(1, sizeof(Abc));
return abcobj;
}

现在,我尝试在我的 D 代码中调用这些函数。

testD.d

module testD;

import std.stdio;
import core.stdc.string;
import core.sys.posix.dlfcn;

extern (C)
{
struct Abc {
ubyte dbtype;
int dbcount;
}
}

int main() {
auto lib = dlopen("Abc.so".ptr, RTLD_LAZY | RTLD_LOCAL);

if (lib is null) {
return -1;
}

void function(Abc* abcobj, char* strA, char* strB) test_string = cast(void function(Abc* abcobj, char* strA, char* strB))dlsym(lib, "test_string");
Abc* function() create_abc = cast(Abc* function())dlsym(lib, "create_abc");

char* strA = cast(char*)("this is string one");
char* strB = cast(char*)("this is string two");

Abc* abcobj = create_abc();
test_string(abcobj, strA, strB);

if (dlclose(lib) == 0) {
return 0;
}
else {
return -1;
}
} // main() function

我使用以下方法编译 testD.d:

dmd 测试D.d

然后运行./testD

当 test_string 输出句子时,strA 的值总是乱码,而 strB 则正常。

为什么会这样??

最佳答案

因为 .so 是用 C 制作的,所以您已经使用 C 链接编译了库,但是当您导入符号,您正在丢弃事实,这意味着 D 尝试使用 D 调用约定来调用代码,这与 C调用约定。

导入函数时,需要指定它,因此 dlsym 行需要如下所示:

extern (C) void function(Abc* abcobj, char* strA, char* strB) test_string =
cast(void function(Abc* abcobj, char* strA, char* strB))dlsym(lib, "test_string");
extern (C) Abc* function() create_abc =
cast(Abc* function())dlsym(lib, "create_abc");

一旦您获得正确的调用约定,正确的结果就会从调用中产生。

关于c - D与C库集成导致输出乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38888873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com