Search code examples
c#c++visual-studiodllimportdllexport

C# project doest not defined entry point for c++ dll written by myself


I'm using a c# socket that pass it to receive data from c++ DLL and return received result to c# and do other staff in c#.

I have a c++ project like this:

SniReceiver.h

#ifdef SNIRECEIVER_EXPORTS
#define SNIRECEIVER_API __declspec(dllexport)
#else
#define SNIRECEIVER_API __declspec(dllimport)
#endif
#include <WinSock2.h>

extern "C" __declspec(dllexport) int __stdcall receive_socket(DWORD socket);

SniReceiver.cpp

#include "stdafx.h"
#include "SniReceiver.h"

#define DEFAULT_BUFLEN 512
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;

extern "C" __declspec(dllexport) int __stdcall receive_socket(DWORD socket)
{
    int  iResult = recv((SOCKET)socket, recvbuf, recvbuflen, 0);
    return iResult;
}

and my c# app:

[DllImport(@"SniReceiver.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int receive_socket(IntPtr sock);

static void Main(string[] args)
{
    IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("192.168.200.1"), 80);
    Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    sListen.Bind(endpoint);
    sListen.Listen(10);
    Socket sClient = sListen.Accept();

    int rec= receive_socket(sClient.Handle);

    Console.WriteLine("Hello World!");            
    Console.ReadKey();
} 

when calling int rec= receive_socket(sClient.Handle); get error

System.EntryPointNotFoundException: 'Unable to find an entry point named 'receive_socket' in DLL 'SniReceiver.dll'.

Remember I've copied SniReceiver.dll beside my c# exe

Picture with DependencyWalker


Solution

  • You are exporting the function as __stdcall , but declaring it in C# as CallingConvention.Cdecl.

    Change the DllImport to:

    [DllImport(@"SniReceiver.dll", CallingConvention = CallingConvention.StdCall)].