FAQ Database Discussion Community


Pinning char[] on P/Invoke call

c#,.net,pinvoke,dllimport
I have object pool of char buffers and passing this buffer on P/Invoke call. Do i need pinning buffer before call or not? First approach: [DllImport("Name", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] private static extern void SomeMeth(char[] text, int size); public static string CallSomeMeth() { char[] buffer = CharBufferPool.Allocate(); SomeMeth(buffer,...

Using a managed buffer in native code after the call returns

c#,dll,pinvoke
I have a buffer I am allocating in C# and passing to native code. I then save a pointer to that buffer: Header Definitions // called when a meter is attached typedef void(__cdecl * lpfnMeterAttachCallback)(); extern lpfnMeterAttachCallback frMeterAttachCallback; // called when a meter is detached typedef void(__cdecl * lpfnMeterDetachCallback)(); extern...

Calling C++ method in C#

c#,c++,pinvoke
I need to call a c++ function from c#. c++ function is BOOL Usb_GetDevicesList(int &iNbDevices, char aszDeviceName[][128]); I tried [DllImport("UsbComm.dll", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] public static extern int Usb_GetDevicesList(int iNbDevices, out byte[][] aszDeviceName); I got error Cannot marshal 'parameter #2': There is...

Get the method name that was passed through a lambda expression?

.net,vb.net,reflection,delegates,pinvoke
Is it possible to retrieve via Reflection the real method name that was passed through a lambda expression? I would like to platform invoke some functions with a better error-handling, then to avoid repeating tons of Marshal.GetLastWin32Error conditionals, I thinked in create a generic method to automate that, where I...

Attempt to load the C runtime library incorrectly in Winamp's in_midi.dll

c#,.net,dll,pinvoke,winamp
I am trying to load a Winamp input plugin and work with it in C#. According to the Winamp SDK, this is the proper way to load a plugin: in_mp3_lib = LoadLibraryW(path); if (in_mp3_lib) { PluginGetter pluginGetter = (PluginGetter)GetProcAddress(in_mp3_lib, "winampGetInModule2"); if (pluginGetter) { in_mp3 = pluginGetter(); } } So I've...

C# Struct to delphi packed record

c#,delphi,pinvoke
I have a function extracted from a delphi dll function func_name(par1: Byte; par2: struct1) : boolean Struct 1 is made up of : struct1 = packed record Number: Byte; arrStr : array[1..8] of struct2; end Moreover struct2 is made up of: struct2 = packed record Code: Byte; Price: Single; end...

PInvoke Implementation on Fields

c#,.net,pinvoke
So today I was browsing around ILSpy to get a better understanding of how .NET performs DllImports on external methods, when I came across something odd: When searching for references to the enum value PInvokeImpl, which is defined in the System.Reflection.MethodAttributes enumeration, I noticed a matching definition in System.Reflection.FieldAttributes. Well...

Reading Byte Array From Delphi Pointer In C#

c#,delphi,pinvoke,marshalling,intptr
I have asked question before. Call Delphi Function From C# I have added two methods like this. C# public interface IStringFunctions { [MethodImplAttribute(MethodImplOptions.PreserveSig)] void SetValueAsByteArray(IntPtr DataPointer, int DataLength); [MethodImplAttribute(MethodImplOptions.PreserveSig)] IntPtr GetValueAsByteArray(out int DataLength); } if (instance != null) { // Sending Pointer of Byte Array To Delphi Function. byte[] inputBytes...

const char* in C#?

c#,.net,dll,pinvoke,marshalling
I try to call a plain C-function from an external DLL out of my C#-application. This functions is defined as void set_param(const char *data) Now I have some problems using this function: How do I specify this "const" in C#-code? public static extern void set_param(sbyte *data) seems to miss the...

Marshal's [In] [Out] Attributes

c#,pinvoke,marshalling,dllimport
I'm invoking an unmanaged function in my C# code. The declaration of this function is as follow: int myFun(unsigned char* inputBuffer, unsigned char* &outputBuffer); I use this function as follow: [DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int myFun([In] byte[] inputBuffer, out IntPtr outputBuffer); byte[] a = Encoding.ASCII.GetBytes("sampletext!"); IntPtr b;...

C# / C++ Asynchronous reverse pinvoke?

c++,c,asynchronous,pinvoke,native
I need to call C# code from a native C/C++ .dll asynchronously. While searching how to do I found that I could create a C# delegate and get a function pointer from it, which I would use inside my native code. The problem is that my native code needs to...

cannot return delphi array in C# array

c#,delphi,pinvoke
i want to use delphi array function in C#. my delphi code: TIntegerArray = array of integer; function Testarray(): TIntegerArray stdcall; export; var res: TIntegerArray2; begin SetLength(res, 10); res[5] := 55; Result := res; end; exports Testarray; C# code: [DllImport("GitaTele.dll", CallingConvention = CallingConvention.StdCall)] public static extern int[] Testarray(); show me...

Marshaling an IntPtr[] inside a struct causes midiStream functions to bug out, but unrolling the array to a bunch of fields works

c#,windows,pinvoke,midi
I'm trying to use the Windows multimedia MIDI functions from C#. Specifically: MMRESULT midiOutPrepareHeader( HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr ); MMRESULT midiOutUnprepareHeader( HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr ); MMRESULT midiStreamOut( HMIDISTRM hMidiStream, LPMIDIHDR lpMidiHdr, UINT cbMidiHdr ); MMRESULT midiStreamRestart( HMIDISTRM hms ); /* MIDI data block header */...

Explain what problems could have this function (if any)

.net,vb.net,winapi,pinvoke,getlasterror
SCENARIO When P/Invoking, I thinked it could be a great idea to simplify/reduct tons of code by designing a generic function that calls the function, then it checks for the GetLastWin32Error I'm using this code: ''' <summary> ''' Invokes the specified encapsulated function, trying to provide a higher safety level...

Pinvoke. Speed up Console.Write();

c#,performance,console-application,pinvoke,tetris
I am writing a c# console tetris game. Once I got to the part that the application was ready. I got to the part where I had to solve lagging. I am writing out like this: static void writeCol(string a, ConsoleColor b) { ConsoleColor c = Console.ForegroundColor; Console.ForegroundColor = b;...

Where to place local dll in a ASP.NET project?

c#,asp.net,exception,dll,pinvoke
I have a ASP.NET project where I need to pinvoke the following function: [DllImport("NetSh.dll")] public static extern int RunAsUsr(string pcs_admin, string pcs_user, string pcs_password); The problem is that i get the following exception when I call the function: Unable to load DLL 'NetSh.dll': The specified module could not be found....

AccessViolationException occured using P/Invoke with Media Foundation Interface in Multithread application

c#,c++,multithreading,pinvoke
I'm using the P/Invoke in C# to call native function from C++ DLL as below: C++ DLL: extern "C" { // Function: Create Wmv video from sequences image. Codec: WMV3 (VC-1) __declspec(dllexport) bool __stdcall CreateWMV(...) { ... } } C# wrapper class. I create the C# wrapper class function to...

How do I have DeleteObject() invoked on hBitmap other than by using P/Invoke?

c#,.net,bitmap,pinvoke,hbitmap
I'm dealing with code that goes something like this (from here) using (var bmp = new System.Drawing.Bitmap(1000, 1000)) { IntPtr hBitmap = bmp.GetHbitmap(); var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } and MSDN says that whenever I call Bitmap.GetHbitmap() I have to call DeleteObject() on the hBitmap to release...

Access violation when calling Delphi DLL from C# in a multi-threaded environment

c#,.net,multithreading,delphi,pinvoke
I am calling a DLL function written in Delphi XE2 from C# using P/Invoke. It appears to be working when calls are made sequentially from a single thread. However, when multiple threads are calling the function, the C# host application throws System.AccessViolationException seemingly at random. Why does the code below...

Unable to load DLL 'LibFlac': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

c#,dll,pinvoke,dllimport
HERE is the link to my project. The error is on line 107: "context = FLAC__stream_encoder_new();" in file: FlacWriter.cs --> I didn't write that file. I got it from HERE So I understand that libFLAC.dll is missing. So I tried all of the below approaches to solve the issue: I...

EnumDisplayDevices - passing null causes error

c#,winapi,pinvoke,null-string
The MSDN documentation for EnumDisplayDevices states that passing NULL as the first parameter to the function returns information about the display adaptor(s) on the machine (passing a string returns information about the device with that name). Various C# examples that I have seen on-line pass null to the function as...

Get pointer to unmanaged memory in C# from C++

c#,pointers,pinvoke,intptr
I've been given a C++ DLL that allocates memory. It has several functions that need me to pass it the pointer to this allocated memory. I'm working in C# so I need to keep this pointer around, so I can pass it back to the C++ DLL when needed. The...

Can't get SendInput() to work

c#,visual-studio-2013,mouse,pinvoke,sendinput
I'm kind of desperate. I have been trying for hours now, but I just can't get SendInput() to work. To be honest, I can't even get it to be recognized. It always says: Error 1 The type or namespace name 'INPUT' could not be found (are you missing a using...

Overhead - Calling C++ function from C#

c#,c++,pinvoke,marshalling
I am calling two C++ functions from C#. While doing that in a iteration for around 1 million call i am seeing a overhead of about 30%. C++ function : EXTERN_C void STDAPICALLTYPE FunctionA(UINT_PTR mathId) { ... ... } In my C# assembly dll as : [DllImport("CPlusPlus.dll")] public static extern...

How to pass Array of doubles from C# to C++ (DLL)

c#,c++,pinvoke,marshalling,dllimport
the C++ function signature is: int Eye_GetPositionSC2(std::string fname_mob, double sensors[9], int &map_x, int &map_y) the C# function signature is: [DllImport(@"eyeWhere.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] public static extern int Eye_GetPositionSC2([MarshalAs(UnmanagedType.LPWStr)]string filename, [In , MarshalAs(UnmanagedType.LPArray)]double[] sensors) the code is compiling good but there is an "AccessViolationexception" while passing the double...

C# to C++ multithreading, any issues to expect?

c#,c++,.net,performance,pinvoke
After a lot of testing i have a dozen algorithms that don't give me satisfactory speed in C# and that work just fine in C++ (implemented the same way, pretty much copy pasted from C# to C++, heavily array based on large data sets). Now i know how to call...

How to check programatically if keyboard is connected or not?

c#,windows,winforms,c#-4.0,pinvoke
I am developing a application in C# winforms. Our application is going to be installed on win8 surface(touch screen device). We want to check if a keyboard is connected via USB then our app will not show soft keypad otherwise it will show. Many methods are avaliable to check for...

Marshal.PtrToStructure crashing on 64bit

c#,crash,64bit,pinvoke
My unit tests crash on this bit of code when running in 64bit. The crash happens on the Marshal.PtrToStructure call on the 2nd iteration of the loop. The "entriesRead" says 4 so it should be able to read correctly, but it does not. The Marshal.SizeOf(typeof(WinAPI.NETAPI32.USER_INFO_4)) is 192 bytes in 64bit....

How can I marshal a Delphi short string using p/invoke?

c#,delphi,pinvoke,marshalling
I have a problem with a variable type from a dll which i am importing in C#. It is written in object oriented pascal and it says it is developed with the Delphi Development Tool. On the manual of the library it says that shortstring is a packed array of...

SetFileTime returning error code 5

c#,file,io,pinvoke,kernel32
I am trying to P/Invoke SetFileTime, but I can't seem to get it to work. It always returns an error code of 5 for me (access denied), and I am not sure why. Here is the code I am using: void Main() { var pointer = CreateFile(@"C:\Users\User\Desktop\New folder\New Text Document.txt",...

Marshal C# string to C++ tchar through streamwriter

c#,encoding,pinvoke,tchar
Related question In C++, I require a TCHAR string (LPTSTR). C# StreamWriters can output ASCII, Unicode, UTF32, etc... Not TCHAR strings. I am not calling a function in C++, I am sending a string message over a named pipe. C#: using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mynamedpipe", PipeDirection.InOut)) using (StreamWriter...

pInvoke in c# (Managed code)

c++,pinvoke
I am trying to pInvoke a C method in c#, but it is giving error; Attempted to read or write protected memory. This is often an indication that other memory is corrupt. C Method; HRESULT FilterVolumeInstanceFindFirst( _In_ LPCWSTR lpVolumeName, _In_ INSTANCE_INFORMATION_CLASS dwInformationClass, _Out_ LPVOID lpBuffer, _In_ DWORD dwBufferSize, _Out_ LPDWORD...

Calling C++ dll from C#. “Cannot marshal 'return value': Invalid managed/unmanaged type combination.”

c#,pinvoke
My Header file. extern "C" class MyFuncs { public: __declspec(dllexport) unsigned char PassImage(unsigned char buffer, int size); }; CPP file. unsigned char MyFuncs::PassImage(unsigned char buffer, int size) { return buffer; } All works well except when i am returning buffer back to my main application. [DllImport("ExampleDLL.dll", EntryPoint = "[email protected]@[email protected]@[email protected]")] public...

How to P/Invoke into kernel32.dll on WinRT 8.1

c#,windows-runtime,windows-store-apps,windows-phone-8.1,pinvoke
I'm trying to use a native API method (GetNativeSystemInfo) that is marked as supported for both phone and desktop Store apps on Windows 8.1. In the documentation, it is listed as living in kernel32.dll. Great! So my first attempt at P/Invoke looked like this: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling =...

Call Delphi Function From C#

c#,delphi,pinvoke,delphi-xe2,marshalling
I have a below DLL source code. library Project1; uses System.SysUtils, System.Classes; type IStringFunctions = interface ['{240B567B-E619-48E4-8CDA-F6A722F44A71}'] function GetMethodValueAsString():PAnsiChar; stdcall; end; TStringFunctions = class(TInterfacedObject, IStringFunctions) public function GetMethodValueAsString():PAnsiChar; stdcall; end; {$R *.res} function TStringFunctions.GetMethodValueAsString():PAnsiChar; stdcall; begin Result := 'test'; end; procedure GetImplementation(out instance:IStringFunctions); stdcall; export; begin...

Pinvoke cdecl convention with char**

c#,c++,char,pinvoke
In summary: I`m trying to use a C++ dll with cdecl calling convention all ran fine unless i get to this method signature: int SaveToBuffer( char **buf, int *buf_size ); from what i have read i should use it like this: [DllImport("entry.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SaveToBuffer")] private static...

Include .dll from C#

c#,pinvoke,dllimport
I have library say tenslib.h, I have changed it to tensLibs.dll using visual Studio 10 C (I have used this). I want to open it using C# window form application. I build it and succeeded. But when I run the application, there is an error: An unhandled exception of type...

What is the best way to wrap unmanaged C++ classes so they can be consumed by .Net managed client applications?

c++,.net,pinvoke,marshalling
We have a win32 C++ unmanaged library (which calls Boost and openCV under the covers). The library contains several public class definitions. The classes themselves expose several methods who's parameters include vectors, shared pointers and callbacks as part of their method signatures. We would like to create a wrapper which...

Print a BMP file to Printer using command

c#,c++,pinvoke
I need to print a BMP file to USB printer using commands. C++ signature is USB_API BOOL Usb_WritePort(BOOL bUseBulkEndp, LPCVOID lpBuffer, DWORD dwNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped); This is my C# signature [DllImport("usbRtb.dll", CallingConvention = CallingConvention.Cdecl)] public static extern Boolean Usb_WritePort(bool bUseBulkEndp, IntPtr lpBuffer, UInt32 nNumberOfBytesToWrite, out UInt32 lpNumberOfBytesWritten, [In]...

C++ function to C#

c#,c++,pinvoke,dllimport
I am totally new to C++ programming. I need to call a C++ function from C#. C++ function is: BOOL Usb_Init(HWND hwnd); I've tried: [DllImport("UsbComm.dll", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool Usb_Init( out IntPtr hwnd); I got the Error message:...

PInvoke with a void * versus a struct with an IntPtr

c#,interop,pinvoke
Imagine I have a function called Myfunction(const void * x); My C# declaration could be MyFunction(IntPtr x); Is this functionally and technically equivalent to struct MyStruct { IntPtr P; } MyFunction(MyStruct x); Or will there be a difference in how they are marshalled. I'm asking this because the library I'm...

Marshalling C-style array of LPWSTR to managed string[] using pInvoke

c#,c++,arrays,pinvoke
I'd like to call an unmanaged method that allocates memory, creates an array of LPWSTRs, and returns it to managed code. I'd like to avoid in/out parameters and writing code to manage memory and variable scopes as much as possible so I decided I would rely on using CoTaskMemAlloc and...

Problems when P/Invoking CertCreateSelfSignCertificate

c#,.net,pinvoke,marshalling,x509certificate2
I was following this article (in it there is a link to a .cs file at the bottom of the page) to generate a self-signed X509Certificate2. The code in the article works but now I want to extend it. I am trying to pass the optional argument, _In_opt_ PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,...

How to properly dispose of pinvoke/unmanaged code

c#,c,pinvoke,safehandle
I have code that needs to pinvoke a c dll, it seems to me that this code should implement idisposible since it touches unmanaged code. I could be wrong so please correct me if this is not true. Reading up on the stuff it seems like I should use safehandles....

C# CopyFileEx - ProgressRoutine : do we really need to close the destination file handle while progress?

c#,pinvoke,kernel32
I tried to close the handle in the ProgressRoutine when the transferred bytes size is greater than or equal to total file length. but the whole operation rarely throws System.IO.IOException : The Handle is invalid. bool result = CopyFileEx(source, destination, new CopyProgressRoutine(CopyProgressHandler), IntPtr.Zero, ref IsCancelled, copyFileFlags); if (!result) { //when...