C#项目没有为自己写的c++ dll定义入口点

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

我正在使用一个 c# 套接字,该套接字将其传递给从 c++ DLL 接收数据,return 将接收到的结果发送给 c# 并在 c#.

我有一个这样的 c++ 项目:

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

和我的 C# 应用程序:

[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();
} 

调用时int rec= receive_socket(sClient.Handle); 收到错误

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

记住我在 c# exe

旁边复制了 SniReceiver.dll

您将函数导出为 __stdcall ,但在 C# 中将其声明为 CallingConvention.Cdecl.

将 DllImport 更改为:

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