gpt4 book ai didi

c# - 你如何在 C++ 中调用 C# 方法?

转载 作者:太空狗 更新时间:2023-10-29 21:07:14 25 4
gpt4 key购买 nike

herehere 他们确实讨论了该做什么,但我似乎无法在 C++ 中找到我的 C# 项目。

我已将 c# 项目作为引用添加到 c++ 项目中,但每当我尝试使用我需要的方法时,它都找不到命名空间。我通过右键单击 c++ 项目并选择“引用”来添加它,然后添加带有添加新引用的 c# 项目。这两个项目都在同一个解决方案中。

在下面的代码示例中,我给出了完整的 c# 代码(usings 除外)和部分 c++ 代码(我试图从中调用 c# 方法的方法)。我还更改了一些命名空间,使其更通用并且不包含任何敏感信息。

c#代码是这样的。

namespace Company.Pins.Bank.Decryption
{

public class Decrypt
{
[DllImport("decryptsn.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr decryptsn(byte[] InpData);
//__declspec(dllimport) char* decryptsn(char* InpData);

public static String Decryption(string param2)
{
byte[] InpData = new byte[255];
InpData = StrToByteArray(param2);
return Marshal.PtrToStringAnsi(decryptsn(InpData));
}

public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
}
}

C++代码

CPReSInterfaceApp theApp;

extern "C" DllExport BOOL WINAPI UserInstruction(
HWND hWnd, HINSTANCE hInst, double* lpNumeric,
TCHAR* lpAlpha1, TCHAR* lpAlpha2)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());

if (lpNumeric == NULL || lpAlpha1 == NULL || lpAlpha2 == NULL)
return FALSE;

ReconcileUHParameter(lpNumeric, lpAlpha1, lpAlpha2);

int iCommand = (int)lpNumeric[0];

lpNumeric[0] = 6;
lpAlpha2 = Company.Pins.Bank.Decryption.Decrypt.Decryption("123456");

return TRUE;
}

最佳答案

您需要添加一个 #using directive to the code 。例如,如果您的 C# dll 名为 Decrypt.dll,请将其添加到 C++ 编译区的顶部:

#using "Decrypt.dll"

您还需要确保调用托管方法的 C++ 代码也使用 /clr 编译器选项编译为托管。

此外,我认为您需要使用 :: 作为命名空间分隔符,而不是 .

lpAlpha2 = Company::Pins::Bank::Decryption::Decrypt::Decryption("123456");

关于c# - 你如何在 C++ 中调用 C# 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5665717/

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