开发者

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

开发者 https://www.devze.com 2023-02-25 01:35 出处:网络
here and here they do talk about what to do, but i seem to be unable to find my c# project in c++. I have added the c# project as a reference in the c++ project but whenever i try to use the method i

here and here they do talk about what to do, but i seem to be unable to find my c# project in c++.

I have added the c# project as a reference in the c++ project but whenever i try to use the method i need, it can't find the namespace. i have added it by right clicking the c++ project and going for 'reference' then added the c# project with add new reference. both projects are in the same solution.

In the below code excamples i have given the full c# code (except for usings) and a part of the c++ code (the method where i am trying to call the c# method from). I have also changed some of the namespacing to be more generic and contain no sensitive information.

the c# code is like this.

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.Te开发者_StackOverflow中文版xt.UTF8Encoding();
            return encoding.GetBytes(str);
        }    
    }
}

C++ code

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;
}


You need to add a #using directive to the code. For example, if your C# dll were named Decrypt.dll, add this to the top of your C++ compiland:

#using "Decrypt.dll"

You also need to make sure the C++ code that calls a managed method is also compiled as managed using the /clr compiler option.

Also, I believe you need to use :: as a namespace separator, rather than ..

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号