Marshal.AllocHGlobal VS Marshal.AllocCoTaskMem, Marshal.SizeOf VS sizeof()

A Windows program always has at least two heaps in which unmanaged memory is allocated. First is the default process heap, used by Windows when it needs to allocate memory on behalf of the program. The second is a heap used by the COM infrastructure to allocate. The .NET P/Invoke marshaller assumes this heap was … Read more

Is it possible to catch an access violation exception in .NET?

You shouldn’t. An access violation is a serious problem: it is an unexpected attempt to write to (or read from) an invalid memory address. As John already clarified, the unmanaged DLL might already have corrupted the process memory before the access violation has been raised. This can have unpredicted effects on any part of the … Read more

Is there a tool that generates P/Invoke signatures for arbitrary unmanaged DLL?

Google quickly found http://www.pinvoker.com (Wayback) (Compatiblity listed as VS2005, 2008, and 2010; it doesn’t seem to have been updated to work with newer versions) Microsoft’s C++/CLI compiler can also do this, if you use /clr:safe and #include the header file, it will generate p/invoke code which you can extract with e.g. ILSpy (free) or Red … Read more

Using C++ Class DLL in C# Application

Simple way assuming class Foo: Create a C++/CLI project, call this FooWrapper. Make FooWrapper depend on the unmanaged dll (however you normally would). Create a managed class ManagedFoo which contains a single private instance field of type Foo*. provide public wrapping functions in ManagedFoo which forward on to the underlying instance field. Optionally (though recommended): … Read more

WinApi – GetLastError vs. Marshal.GetLastWin32Error

You must always use the Marshal.GetLastWin32Error. The main problem is the garbage collector. If it runs between the call of SetVolumeLabel and the call of GetLastError then you will receive the wrong value, because the GC has surely overwritten the last result. Therefore you always need to specify the SetLastError=true in the DllImport-Attribute: [DllImport(“kernel32.dll”, SetLastError=true)] … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)