How can I call my c++ program in c# gui?

Can I call this c++ code in c# gui? If so, how could I do this?
My c++ function:

int getSize(const char *file) {
    HANDLE hFile;

    LPCWSTR inFile = (LPCWSTR)file;
    hFile = CreateFile(
        inFile,
        GENERIC_READ,
        FILE_SHARE_READ,
        0,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );

    DWORD dwFileSize;
    dwFileSize = GetFileSize(hFile, NULL);
    CloseHandle(hFile);
    return dwFileSize;
}

I would like to use it in c# like this:

int fileSize = getSize(DecryptionOpenFile.FileName);

Upvotes: 1

Views: 128

Answers (1)

Guillaume P.
Guillaume P.

Reputation: 163

You just need to import your DLL into your C# GUI project and make a wrapper around it.

Here is a sample :

public static class IncDll
{
    [DllImport("myLibrary.dll")]
    public static extern void MethodName(ParameterList);
}

Then in your code, you just need to call it like this :

IncDll.MethodName(params);

You can also have two projects, one in C++/CLI and another one in C#.

The C++/CLI is wrapping native C++ API.

Then add reference to C++/CLI library into C# and you will be able to use native library through the wrapper.

Upvotes: 2

Related Questions