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

How do you call a c# method in c++?

本文关键字:方法 调用 c++      更新时间:2023-10-16

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

我已经添加了c#项目作为c++项目的参考,但每当我尝试使用我需要的方法时,它找不到命名空间。我通过右键单击c++项目并选择"参考"来添加它,然后添加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++编译器的顶部:

#using "Decrypt.dll"

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

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

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