无法从C应用程序访问C ++ DLL中的变量 [英] Can't access variable in C++ DLL from a C app

查看:82
本文介绍了无法从C应用程序访问C ++ DLL中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解决旧版Visual C ++ 6应用程序的问题.在C ++ DLL源代码中,我已经输入

I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put

extern "C" _declspec(dllexport) char* MyNewVariable = 0;

这将导致MyNewVariable在导出表中显示(很少修饰)(如dumpbin/exports blah.dll所示).但是,我不知道如何声明该变量,以便可以在C源文件中对其进行访问.我尝试过各种方法,包括

which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including

_declspec(dllimport) char* MyNewVariable;

但这只是给我一个链接器错误:

but that just gives me a linker error:

无法解析的外部符号"__declspec(dllimport)char * MyNewVariable"(__imp_?MyNewVariable @@ 3PADA)

unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA)

extern "C" _declspec(dllimport) char* MyNewVariable;

根据Tony的建议(以及我之前尝试过的),它会产生不同的预期装饰,但仍然没有将其删除:

as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:

未解析的外部符号__imp__MyNewVariable

unresolved external symbol __imp__MyNewVariable

如何编写声明,以便可以从C应用程序访问C ++ DLL变量?

How do I write the declaration so that the C++ DLL variable is accessible from the C app?

正如botismarius和其他人(非常感谢所有)所指出的,我需要链接DLL的.lib.为了防止名称被篡改,我需要在C语言中声明没有修饰符的名称,这意味着我需要使用.lib文件.

As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.

推荐答案

您必须链接编译DLL后生成的lib.在项目的链接器选项中,您必须添加.lib文件.是的,您还应该将变量声明为:

you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the .lib file. And yes, you should also declare the variable as:

extern "C" { declspec(dllimport) char MyNewVariable; }

这篇关于无法从C应用程序访问C ++ DLL中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆