如何访问c文件中public class函数修改的c++全局变量

how to access c++ global variable modified by public class function in c file

DialogReprog.cpp

unsigned char PasswordValue[16];
unsigned char SystemKeyValue[16];

void CDialogReprog::OnOK()
{
// TODO: Add your control notification handler code here
char *ptr;
size_t count=0;

UpdateData();
TCHAR buffer[50];
GetDlgItemText(IDC_PASSWORD, buffer, 50);
ptr = (char *)buffer;
for(count = 2; count < 6; count++)
{
    sscanf(ptr, "%2hhx",&PasswordValue[count-2]);
    ptr += 2;
}

GetDlgItemText(IDC_SYSKEY, buffer, 50);
ptr = (char *)buffer;
for(count = 2; count < 18; count++)
{
    sscanf(ptr, "%2hhx",&SystemKeyValue[count-2]);
    ptr += 2;
}

UpdateData(FALSE);
CDialog::OnOK();

}

需要访问 C 文件中的 PasswordValue 字节数组来访问数据,当我调试时我可以看到数据在手表中可见 window(我使用 Visual Studio 2005 作为我的项目)

如果您想在 C 代码中访问 C++ 代码中的内容,您需要了解两种语言在编译和链接方面的一些主要区别。每种语言都使用 name mangling。这意味着相同的 variable/function 将具有不同的链接器名称,具体取决于您是用 C 还是 C++ 创建它。这也是为什么您可以在 C++ 中重载函数但不能在 C 中重载的原因。

在解决您的问题时,普遍接受且最简单的解决方案是声明这些变量,就像它们使用 C 风格的重整一样。为此,您只需像这样使用 extern "C"

extern "C"{
    unsigned char PasswordValue[16];
    unsigned char SystemKeyValue[16];
}

在这种情况下,您将能够从 C 文件访问这些变量。

这对函数也同样有效,但这也意味着您不能使用 C++ 功能,例如使用这些名称进行重载(如果您尝试使用,您的链接器会报错)。