Using cgwin compiled dll from c-source in C #, error reading write-protected memory in socket (), fork () and similar

I have a source written in C that uses a lot of sender and socket listener calls, and then a few working functions. The socket is multicast as well as uni cast.

It has many read operations. I compiled it using cygwin, generated exe, and it worked fine on all window options. Meanwhile, when I generated a dll from the same and tried to use it in C # via DLLimport, it works fine until it reaches the next line

if((sendFd = socket(AF_INET,SOCK_DGRAM,0)) < 0) 

Visual studio gives an error message:

 Attempt to read write protected memory, or other memory is corrupt. 

Without all the socket files or fork (), it works just fine, performing basic operations like string manipulations, etc.

+4
source share
1 answer

If I understand you correctly, are you trying to create a [DllImport] native library compiled with Cygwin in a .NET assembly?

Well, this is a recipe for disaster:

You are trying to use two different C runtime libraries in the same application. Cygwin provides its own implementation of various system functions; it is not just a shell around the corresponding Windows APIs. There are a few things that may go wrong:

  • The executable file contains the initialization and start code, which runs before the call to main() . This code is automatically generated by the compiler and initializes the C Runtime. You will get around this code with P / Invoking your DLL.
  • Cygwin uses its own socket code, which requires some low-level system calls to interact with the network card - and since Cygwin uses its own implementation, it does this during Windows runtime.

If you want to use sockets in the native DLL used in the .NET application, you need to use Winsocks and compile it with the Microsoft compiler, so it is associated with native Windows libraries.

You can, for example, use Visual Studio 2012 Express for desktop for this.

0
source

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


All Articles