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

他们在这里和这里谈论要做什么,但我似乎无法在c ++中找到我的c#项目。

我已经在c ++项目中添加了c#项目作为参考,但每当我尝试使用我需要的方法时,它都找不到命名空间。 我通过右键单击c ++项目添加它并进入’reference’然后添加了c#项目并添加了新的引用。 两个项目都在同一个解决方案中。

在下面的代码示例中,我给出了完整的c#代码(使用除外)和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指令 。 例如,如果您的C#dll名为Decrypt.dll ,请将其添加到C ++ compiland的顶部:

 #using "Decrypt.dll" 

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

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

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