How to use C ++ dll from C #

I am trying to include a C ++ library (DLL) in my C # project, but every time I do this, I get the following error message in VS2012

A reference to 'C:\Users\HiepDang\Desktop\mydll.dll' could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.

When I try to add Com + Component, I get the following error message in the window

One or more files do not contain a library of components or types. These files cannot be installed.

Error 80110425 has occurred.

An unknown error has occurred. You must check all the documentation for the solution. If additional information is not available, contact technical support.

I follow the flow here and here , but my problem is not resolved.

In C ++, I can use dll like:

    //Header
    extern "C" __declspec( dllimport ) int mymethod(const char *key, char *data, size_t buflen);

    //Code test
    const char* key = "test";

    char* data = new char[1024];
    int buflen = 1024;
    int result = mymethod(key,data, buflen);

In C #, I use dll like:

    //define dll
    [DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern int mymethod([MarshalAs(UnmanagedType.LPTStr)]string key, [MarshalAs(UnmanagedType.LPTStr)]string data, uint buflen);

    //method test
    private static int testdll() 
    {
        string key = "123456789";
        string buf = string.Empty;
        mymethod(key, buf, 1024);
        return 0;
    }

Can you tell me about any solutions to solve it.

P.s: . , -

: dll. "", 8-13 , mymethod "buf". "buf".

+4
3

# StringBuilder()

//define dll
[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int mymethod(string key, StringBuilder data, IntPtr buflen);

//method test
private static int testdll() 
{
    string key = "123456789";
    StringBuilder buf = new StringBuilder(1024);
    mymethod(key, buf, (IntPtr)buf.Capacity);
    string buf2 = buf.ToString()
    return 0;
}

, size_t IntPtr, 4 x86 8 x64.

+2

cpp,

extern "C" __declspec( dllimport )

extern "C" __declspec( dllexport )

dp cpp "mydll.dll" outdir #.

, byte [] char * , , .

[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int mymethod([MarshalAs(UnmanagedType.LPTStr)]string key, byte[] data, uint buflen);

.

MSDN

, .

var key = "A key";
var data = new byte[10];
//fill data
mymethod(key, data, (uint)data.Length);
+1

, DLL ( , , C ++), , DllImport, ", DLL ". "DllImport"? ++ com, regsvr32, dll Visual Studio com, dll ( , , ), , nameoflibrary.interop.dll. , MyExecRefsDll.dll, , MyExexRefs.Interop.dll. , . dll ++ com, atl ++, dotnet (Iam, ++ dll, dll.) , dll. tlb, lib, dll .

0
source

Source: https://habr.com/ru/post/1588923/


All Articles