奇怪的DllImport行为(仅在Unity3d中)

本文关键字:仅在 Unity3d 行为 DllImport | 更新日期: 2023-09-27 18:01:16

我用C为c#编写了一个简单的Winsock包装器。当我使用Socket.Accept()在一些线程和客户端。在主线程中连接-有时会收到DllNotFoundException.

系统。DllNotFoundException:异常类型的系统。日志含义抛出"notfoundexception"。(包装管理到本机)TcpWrapper:ES_ConnectClient (string,int) atTcpClientSocket。(系统连接。字符串地址,Int32端口)[0x00000]在C: ' ESCore ' TcpClientSocket.cs: 21

TcpClientSocket。连接呼叫

[DllImport("ESocket")]
public static extern int ES_ConnectClient(string ip, int port);

我不知道为什么这种事很少发生。

一些代码:

listener = new TcpListenerSocket(50231); //calling bind from library here
if (listener.Start()) //calling listen from library
{
    thread = new Thread(new ThreadStart(Listen));
    thread.Start();

    client = new TcpClientSocket();
    if(client.Connect("localhost", 50231)) //exception here!
    {
        ...
        client.Close();
    }
}
线程代码:

void Listen()
{
    while (m_Running)
    {
        if (listener.Pending()) //select from library
        {
            TcpClientSocket socket = listener.Accept(); //accept from library
            if (socket != null)
            {
                ...
                socket.Close();
            }
        }
    }
}

监听器也在库中。

库代码:http://pastie.org/private/hdgl9zqxfjt2arlkj11q

更新:这只发生在Unity3d中。

奇怪的DllImport行为(仅在Unity3d中)

这是一个简单的"文件未找到"错误消息。您从未说过"并且我确保DLL存在",因此这是可能的失败模式。

你必须确保Windows可以找到DLL,它应该出现在与EXE相同的文件夹中。选择你的c#项目。项目+添加现有项目,选择ESocket.dll文件,使其添加到您的项目。选择它并切换到Properties窗口。将"复制到输出目录"选项设置为"Copy if newer"。如果DLL是由解决方案中的另一个项目构建的,那么一定要设置项目依赖项,以便始终先构建项目。重建项目

这确保ESocket.dll始终存在于构建目录中,并且Windows总能找到它。