Click here to Skip to main content
15,890,579 members
Everything / PInvoke

PInvoke

PInvoke

Great Reads

by Nicolas Dorier
Configure the HTTP traffic on your local machine. A nice alternative for netsh http.
by Dev Leader
Are you excited to get your Myo armband from Thalmic Labs? If you're a C# developer, then check out this open source library to help you control your Myo! The post appeared first on http://www.DevLeader.ca.
by Steffen Ploetz
How to develop Linux/Unix (X11) GUI applications in C# efficiently without dependencies to GUI frameworks like GTK or KDE. Description of composite widgets.
by Maxim Kartavenkov
Article describes basic task which are requre to solve for developing your own DirectShow Splitter filters.

Latest Articles

by Ronald M. Martin
A walk-through of the front end of a convenient ad blocking application that lives behind a notify icon
by Ronald M. Martin
This article provides a walk-through of the front end of a convenient ad blocking application that lives behind a notify icon.
by Ronald M. Martin
This series of articles explores a new WPF-friendly wrapper class for Shell_NotifyIcon.
by Ronald M. Martin
This series of articles explores a new WPF-friendly wrapper class for Shell_NotifyIcon.

All Articles

Sort by Updated

PInvoke 

14 Jul 2010 by #realJSOP
Here it is according to Microsoft (found with google):http://msdn.microsoft.com/en-us/library/aa377274%28VS.85%29.aspx[^]A little googling (search phrase used was "C# rasentry") turned up some code:http://www.dotnet247.com/247reference/msgs/41/206366.aspx[^]It's not that hard to...
3 Oct 2016 by #realJSOP
0) Make double-damn sure your method prototype is correct.1) Change the "out" parameters to "output".2) Why are you calling an unmanaged DLL to do that when .Net provides exactly the same functionality?
22 Feb 2021 by 11917640 Member
Marshal::PtrToStructure: Marshal.PtrToStructure Method (System.Runtime.InteropServices) | Microsoft Docs[^] Additional overloads: Marshal.PtrToStructure Method (System.Runtime.InteropServices) | Microsoft Docs[^] Marshal.PtrToStructure Method...
8 Jul 2013 by _Asif_
As elaborated by SA you are passing null to sample_getinfo that caused the error. A quick solution to allocate memory to this pointer. change this line char* Info;to thischar* Info = new char[255];and try again.
27 Mar 2011 by Alexiy
As in C # use the following code:Cutting simpleHeader.hextern "C" class __declspec (dllexport) MyClasspublic:{bool Open(int port, int baud);}Prog.cppextern "C" __declspec (dllexport) bool MyClass::Open(int port, int baud){ char COM_string[20]; ...
15 Aug 2011 by andreas1024
Hi.I have a strange problem with P/Invoke: every PInvoke call produces a StackOverflowException in mscorlib.dll. Even LoadLibrary or GetProcAddress. The strangest thing is that the code is running fine, I get the right return value back and so on. But the Exception is thrown a short time...
7 Oct 2012 by Andriks
A MessageBox replacement with some much needed extras
14 Apr 2018 by Andy Galluzzi
Join me to create the most advanced yet most simple to use full duplex MMF based IPC for Windows
12 Mar 2014 by ankit sharma
I want to use GetClusterInformation() function to get the version of MSCS . below is the code snippet I am trying. Any help is much appreciated.public static class Test_LoadLibrary { [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] static extern...
9 Mar 2013 by anssary2010
I try to bulid application to make new appliction bar using SHAppBarMessage but icant any body can help me explain step by step using SHAppBarMessage in .net manged code
31 Jul 2011 by apaka
Unmanaged code calls my functions. In first function I sould pass back pointer to my managet object. Sometimes later some of my othrer functions got called with that same pointer as one of parameters . I sould dereference it use it to perform some calculations and then if it is not neaded...
14 Aug 2011 by apaka
I'm trying to convert a device name of the form"\Device\HarddiskVolumeXX" to a name of the form "\\?\Volume{GUID}. How can I do this in C# ?
21 Feb 2012 by Areff
hi, every bodyi have a little problem in p/invoke :my function signature in c++ is some thing like thisReadData (char* data);that i will pass address of string to that fucntion and my data will be filled in the address (function works fine but just data marshaling goes wrong and...
8 Aug 2012 by AS01234
Help with passing structure from unmanaged c++ dll to c# ?I am struggling with passing a structure from an unmanaged third party c++ dll back into my c# application. The dll is for a spectrometer. All of the other commands to the spectrometer work fine except this one. I am pasting more...
11 Oct 2012 by AS01234
The reference from Philip Stuyck was very helpful, but I want to also acknowledge receiving help from the company that makes the spectrometers (mightexsystems.com). I still don't like the solution, because now it uses unsafe code in the wrapper, essentially c++, to de-reference the...
6 Sep 2013 by AS01234
I am talking to a low-cost Tucsen camera through it's dll. Most of the commands are working, but there is one command that I can't seem to marshal correctly. The signature of the call in the CamApi.h file is:CAM_API int GetRoi(int *pPtX, int *pPtY, int *wid, int *hei, const char...
15 Sep 2013 by AS01234
The folks at Tucsen camera were very helpful. I sent them the project. They tested it, said that they modified it a little, and sent it back. It still gave the same result, but since it was working for them when they sent it I became more confident that the pinvoke code was working all along,...
26 Aug 2010 by Bassam Alugili
Inserts tabular text into Microsoft Word document
23 Jan 2014 by BillWoodruff
1. same question Ron Beyer asked you: please define 'external application windows' in this context precisely.2. is this a WindowsForms project ? if not, what's the context: WPF ? ... C++ ?3. is there one-and-only-one window that if moved moved all others ? if more than one window can...
5 Apr 2015 by Bjørn
Using ffmpeg DLLs directly in C# to extract frames and create a thumbnail sheet
28 Nov 2014 by bling
Try the Marshal functions instead of VirtualAlloc. Also, use IntPtr instead of void * for eventBuf and privData. Try a "ref ushort" for eventBufSize and numEvents.[DllImport("csta32.dll", CallingConvention = CallingConvention.StdCall)]public static extern unsafe int acsGetEventPoll(uint...
9 Feb 2013 by CHill60
Replace private delegate bool EnumResTypeProc(IntPtr hModule, string type, int param);private bool EnumResTypeProcInstance(IntPtr hModule, string type, int param)withprivate delegate bool EnumResTypeProc(IntPtr hModule, int type, int param);private bool EnumResTypeProcInstance(IntPtr...
26 Jul 2010 by Christian Graus
Apart from the obvious answer ( use google/read a book ), www.pinvoke.net has signatures for a lot of dll methods that people like to import and use in .NET.
25 Jul 2012 by Christian Graus
If you have a vanilla dll you're calling, then you can use pinvoke if you get the code right. If you're writing the dll, you're better off using COM to get it to work with VB6, assuming you have no choice in that question.
29 Oct 2014 by Christian Sack
Hello guys,First of all: sorry for my broken english...And now to my question:I'm looking for an equivalent for the function IcmpSendEchoEx2.I am new to the pinvoke thematics and so I tried it with the following method:It is a modified version of the pinvoke.net article:...
29 Oct 2014 by Christian Sack
So here is the full working code: public static PingReply Send(IPAddress srcAddress, IPAddress destAddress, int timeout = 5000, byte[] buffer = null, PingOptions po = null) { if (destAddress == null || destAddress.AddressFamily != AddressFamily.InterNetwork ||...
23 Jan 2015 by clemhindie
Hi every body,I'm working on Winform project in C# and I have to use a C written dll to communicate with an OpenVMS machine.Some methods are using a C char** or an unsigned char** parametersWhen i try to "translate" those parameters in string array, byte array or a StringBuilder and...
16 Aug 2021 by Code Fan
All .Net managed threads within the same app domain share the same memory heap, no need to do anything extra, unless, of course, you're working with multiple threads from different app domains or processes.
25 May 2017 by CPallini
Quote: [MarshalAs(UnmanagedType.U8)]ulong verb, [MarshalAs(UnmanagedType.U8)]ulong verb2 That should be, instead [MarshalAs(UnmanagedType.U4)] uint verb, [MarshalAs(UnmanagedType.U4)] uint verb2 or, simply: uint verb, uint verb2
8 Feb 2012 by creizlein
I have been facing some issues lately with Pinvoke calls to native functions of advapi32.dll from managed code and i haven't found yet a way to make it work properly, facing multiple problems related to the classic "A call to ... has unbalanced the stack" and "attempt to read/write protected...
24 Apr 2014 by creizlein
I'm trying to get a per disk ( or per partition ) usage report, aka read/write bytesi know i can use performance counters for this, or even WMI, but i would like to achieve this same result by using native WinAPI with p/invokedoes anyone can point me to the right functions or libraries to...
24 Mar 2011 by Dan Buskirk
Accessing Industry-Standard Linear Algebra Libraries from .NET Code
18 Aug 2012 by Dan Randolph
C# interop using platform invoke and C++ vectors to implement fast searching and selection on index keys
4 Nov 2015 by DanielBrownAU
One way which comes to mind (and it may not be best practice tho)... may be to wrap the P/Invoke calls in a try/catch/finally block to handle with any exceptions generated by the calls.Furthermore, any access/calls to the libraries could be placed into its own central class and error...
11 Feb 2013 by Dave Elliott
This article provides a practical solution to clicking the button on a popup window.
8 Feb 2012 by Dave Kreskowiak
The biggest culprit of "A call to ... has unbalanced the stack" is you declared a type as Long instead of Integer. This is very common if you used a Declare you found on the internet and it belongs to VB6 code.A Long in VB6 is a 32-bit signed integer. A Long in VB.NET is a 64-bit signed...
28 Jan 2013 by Dave Kreskowiak
First, if you've got the VB6 code calling this .DLL, why are you calling the VB6 code from C#?? Just bypass the VB6 code and go straight to the .DLL!Second, You can't call a VB6 function that returns Variant. There is no equivilent type in .NET. You have to declare the actual type being...
15 Feb 2013 by Dave Kreskowiak
WM_SETFONT is NOT for setting the applications font selection. It is only for changing the font a window is rendered with, such as the text editor window inside Notepad. The problem is Notepad maintains it's own font settings and objects, as does every other application in the world, which...
24 Nov 2009 by DaveyM69
If I understand what you've posted correctly, the first parameter is the pointer to a byte array that is created in memory by the API. If this is the case then passing a value to it (by using ref or nothing) will probably not suceed - you may need an out there. The problem with this is you will need
25 Nov 2009 by DaveyM69
Have you tried using an IntPtr for the first parameter but without the out? [DllImport("FlyCAMm1_AV.dll")]private static extern bool Capture_A_Frame( IntPtr pretBuff, out int pdSize);IntPtr pretBuff = IntPtr.Zero;int pdSize;bool result = Capture_A_Frame(pretBuff, out pdSize);
26 Nov 2009 by DaveyM69
In that case it is asking for the pointer to an existing byte array and it's size, not creating one as was implied by the [Out] in the documentation.So, what you need it seems is to create a byte array, get it's pointer and pass that along with it's size. The function declaration will be:[Dl
6 Feb 2015 by DelphiCoder
Is there a function on the Win32 DLL to save this data to a file? If so, then you could save the file to a temporary location, then use a .NET Reader or even memory map the file for random access.I wrote a log reader once that quickly read and scrolled through logs greater than 4 Terabytes...
6 Oct 2014 by Dev Leader
Are you excited to get your Myo armband from Thalmic Labs? If you're a C# developer, then check out this open source library to help you control your Myo! The post appeared first on http://www.DevLeader.ca.
12 Aug 2018 by Dilan Shaminda
I am using Win32 API functions to register the current program in the Clipboard chain. Below function retrieves the window handle of the current owner of the clipboard. The problem is GetCaptionOfWindow always return null. [DllImport("user32.dll")] public static extern IntPtr...
22 Aug 2012 by dsandru1
I have a DLL that I have imported using P/Invoke and I am trying to pass a structure of character pointers to. DataIn will be filled with an array of hex bytes, and DataOut will be filled during the AssembleSecurityPacket(). I am having trouble getting the dll to fill the output array, DataOut....
24 Aug 2012 by dsandru1
I figured out how to do this.I changed my struct to look like this: [StructLayout(LayoutKind.Sequential)]public class sSecurityLayer{ public byte Header_no; public byte Code; [MarshalAs(UnmanagedType.LPStr)] public string DataIn; public int DataInLen; ...
25 May 2017 by DSomesh
I have a c++ function which I am calling from c# using pinInvoke. Following is my cpp method- int test(DWORD verb,DWORD verb2 ) { return verb2 *100; } My function is exposed as - extern "C" { __declspec(dllexport) int test(DWORD verb, DWORD verb2); } Following is my c# code where I am...
31 May 2012 by Duc Huy Nguyen
Hi,I have a C function like this:double* foo() // function return array of 10 double{double* matrix = (double *)malloc(10 * sizeof(double));return matrix;}how can I write in the wrapper class? Should I do that?[DllImport("...")][return:...
31 May 2012 by Duc Huy Nguyen
Hi there,I wrote in C a struct like thatstruct IMAGE { unsigned int x, y; unsigned char **data;};Could anybody please tell me how to marshall this struct to use in C#?my solution does not work.[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]public...
1 Jul 2010 by emicroxxx
Transforming ILMerge.exe to DLL [for convenient usage only]
21 Nov 2014 by eRRaTuM
hi,DeviceIoControl(volumehan...
22 Feb 2021 by Fazi_13
I am currently using delegate from c# to C++ dll i am passing the ref struct to get the value of struct from c++ dll,with out using call back i can able to get the struct value using marshalling.but for dynamic purpose i am using Delegate...
22 Feb 2021 by Fazi_13
Hai, in my application i am using Pinvoke method from c# wpf to C++ dll.i created the same structure in c# which was in c++ dll and i am calling the method with ref of my struct from c# and then there is no problem.for some dynamic purpose i am...
25 Feb 2021 by Fazi_13
class Node { string Name; List NodeList=new List(); } Here is my list,so each an every node contains list and name i need to iterate through all the lists to find out match my condition on any of the lists What I have tried: I...
6 Jun 2021 by Fazil13
I'm trying to do an interop to a C# structure from C++. The structure c# public static IntPtr tempNode = IntPtr.Zero; and also i am using Marshal.PtrToStructure, Marshal.PtrToStringAuto as per requirement. now i am trying with 64bit compiled...
16 Aug 2021 by Fazil13
I am Developing wpf application,in my application i used creates a number of thread to access a same c++ dll for specific operation i dont know how to do it? What I have tried: for refernce i used for loop for(int i= 0; i
28 Jan 2013 by Fiona.fj
I want to PInvoke a function written in VB6 from C#. The VB6 code that calls the DLL is declared like this:Declare Function ApplyNNet Lib " location of the DLL file" (MyNNetType As String, MyAddress As String, MyInput() As Double) As VariantMy C# version looks like...
24 Nov 2014 by George Jonsson
Platform Invoke is used to call Win32 functions from managed code.See PInvoke.net/[^]For calling managed code from unmanaged code one approach is to use COM Interop where COM interfaces are exported from the managed code.See COM Interop Part 2[^]So yes, you are right in your assumptions.
19 Jul 2021 by Greggo
I have written C++ code that is able to read from and write to a com port using the Win32 API method ReadFile. The code is for the purpose of sending HPGL instructions to a legacy graphics plotter and retrieving status data from it. I have...
3 Oct 2016 by Gregory Haberek
The library you're calling is using cdecl calling convention, but the default for C# is winapi, a.k.a. stdcall. Change your DllImport call to look like this instead:[DllImport("mydll.dll"), CallingConvention=CallingConvention.Cdecl)]extern static bool GetFolderSize(string...
30 Nov 2012 by gxsheng
Hi ,guys, I am making a program on LINUX , with MONO as GUI and OpenGL/X11/C++ as renderer . The connection between them is P/Invoke. Worrying about effeciency , I decide not to use CSharp wrapper of OpenGL directly.So the structure is like this : ...
4 Jul 2020 by honey the codewitch
How to marshal structs that the .NET marshaller just can't handle without a lot of help
11 Jul 2020 by honey the codewitch
Exploit the memory layout of your data to make your P/Invoke code more accessible and maintainable
22 Jul 2020 by honey the codewitch
Diving into some of the core plumbing behind the Windows operating system
17 Aug 2013 by Ian A Davidson
Hi all,I've been running the static Code Analysis Tool (aka FxCop) on some code I've "inherited", in order to try to improve it. One of the warnings it gives me is as follows (my emphasis added):CA1901: Microsoft.Portability: As it is declared in your code, parameter 'PathName' of...
7 Jan 2013 by Jason Curl
Describes the usage of Asynchronous I/O with I/O Completion ports with .NET
3 Jul 2014 by Jhone Mitnick
You can set running programs to ontop of window stack (application float above other windows).
13 Jul 2018 by Jochen Arndt
Call GetLastError() when the function fails. The error code might help finding out what is wrong. I guess it is invalid parameter here. Note that all parameters of the API function are pointers. So it should be probably (not tested): [DllImport("Setupapi.dll", SetLastError = true, CharSet =...
6 Feb 2014 by Johannes Bildstein
I've been trying to P/Invoke a *.framework file on a mac with C# but always get a DllNotFoundException.I tried to follow this guide but no luck.The .framwork file is in a subfolder right beside the application.The config file looks like this:
28 May 2015 by Johannes Bildstein
The best and recommended way is to use this:[DllImport("@executable_path/../Frameworks/EDSDK.framework/EDSDK")]The framework files should be in the Frameworks folder and with the DllImport attribute you use standard C# and not some Mono xml-config.ok I found the problem. There are three...
23 Jan 2015 by KarstenK
Take a look on my article and code Calling All Stations. It handles the stuff converting C++ and C# strings and function calling between the runtimes.
22 Sep 2019 by KarstenK
Writing a C# interface isnt to hard. Take a look at my article handling C# interop. Use the Visual Studio Community Edition. Because of the complexity of your library it is best when you write it yourself. The chances that someone will help you are very low.
25 Jul 2012 by kash_sheetansh
Hi! I converted a VB6 project using VS2010 and got an Interop DLL along with the Project. Now i wish to call the certain methods from the DLL. I tried generating the .tlb file using TlbImp so to use the same in RCW but cant, i get an error stating: not a valid type library. I tried to...
28 Aug 2012 by kash_sheetansh
24 Apr 2012 by kkhippytch
Hi!I have an unmanaged DLL (written in C++) and going to call it from the managed code through the P/Invoke.DLL implements a sort of "gateway" to the stock trading server and is written so that at first we should establish a connection to the required trading server (host, port, login,...
30 Sep 2011 by koleraba
Hi everybodyI have a 3rd party dll, which I want to use in my app(.net framework, c#4.0). Dll is used to control IR learner hardware component. Below is the header file for the dll. extern "C" {/******************** CALLBACKS **********************///Callback called when the status...
12 Dec 2011 by koleraba
HiI am trying to use a third party native dll. in my .net application. I am using c#. The function in native dll. has the following declaration:void _stdcall pir_learnCCF( const char * serial, unsigned char state );With the PInvoke Interop assistant I get the following...
31 Jan 2012 by koleraba
I am creating a setup(installer) file with Visual studio installer project. I created a custom installer class that extends a System.Configuration.Install.Installer class. I overided the Install method, and basically what I do is start an external exe. This exe file is a custom application...
12 Sep 2011 by Kunal Chowdhury «IN»
How to open the "Run Dialog" directly from the Silverlight 5 application
22 Aug 2012 by Kuthuparakkal
few ideas will get you started: char* : string PrefIn ="mypref"; unsafe { IntPtr ptrPrefIn = Marshal.StringToHGlobalAnsi(PrefIn); char* _ptrPrefIn = (char*)ptrPrefIn.ToPointer(); } Structure:object _oStruct ; // some...
9 Jun 2013 by Kuthuparakkal
You need to initialize dwTypeData and cch data members...List ls = new List();IntPtr hMenu = Win32.GetMenu(hWnd); if (hMenu.ToInt32() != 0) { char[] szString = new char[256]; for (int i = Win32.GetMenuItemCount(hMenu); i >= 0; i--) {...
28 May 2013 by ledtech3
Updated:I have been trying now for some time to find a way to list the owner, groups, and DACl of a system service.The built in SC.exe utility will return the DACL but not the Owner or groups.After digging thru the Object browser for some time it appears that there is no straight forward...
31 May 2012 by lewax00
[DllImport(".....
28 Aug 2012 by lewax00
The first set of errors (maybe all of them) should be solved fairly easily: . is not used for namespaces in C++/CLI, :: is, so...
1 Jun 2018 by lewisv
I have an c dll that I need to call from my c# application. I have it communicating with the dll, but I am having issues with callbacks. The c looks like this. typedef void (CDECLCALL_CONV *ConnectedCB) (DPHandle hdl); typedef struct { unsigned int size; // sizeof(DPcbs) ConnectedCB...
23 Jan 2012 by Lucas Santos Sanches
Hi all.I've got a problem while working with SetupApi calls.I need to retrieve a device type from a device.The I used to get it: _ Public Shared Function SetupDiGetDeviceRegistryProperty( _ ByVal DeviceInfoSet...
23 Jan 2012 by Lucas Santos Sanches
OKI found other way to do it.Actually, I was not trying to know a "devicetype" but I want to know if it is removable.I use DeviceIoControl and IOCTL_STORAGE_GET_HOTPLUG_INFO.Thanks.
12 Dec 2013 by Luiey Ichigo
Hi coders,I'm facing a problem here. I'm not C++ person. I do VB.Net. I got a .h and .cpp file. Some of the code is successfully translate but there is 1 thing from the code that I can't understand. Can someone who experience the C and VB.NEt to see this. Below are my code:From...
22 Jan 2014 by Lumír Kojecký
This tip shows a simple way to obtain information about currently playing song in Windows Media Player 12 in C# language.
14 Aug 2014 by LuOPa
Hi allI'm working on a custom outlook addin where I need to subclass the appointment window. This works basically pretty well following the principles mentioned in the following ariticle: http://www.codeproject.com/Articles/27262/Additional-custom-panel-in-Microsoft-OutlookI'm...
25 Feb 2021 by Maciej Los
You need recursion. See: c# - Find node when traversing tree - Stack Overflow[^]
28 Jan 2018 by manojmaks
I am creating a windows service that will print pdf in time interval. What I have tried: I have done some research on this and found a class public class ProcessStarter : IDisposable { #region Import Section private static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000; private...
17 Apr 2014 by Martin Solovey
Simple API to Register/Listen for HotKey in .NET applications
17 Dec 2014 by MasterCodeon
Hello Everyone again!i had an idea to minimize or close my app when i press a key combo(like CTRL+E or something). Now i know how to minimize and close the app, i can do that either using the win api using the DestroyWindow method or the CloseWindow(this is to minimize the app) methodi also...
6 Feb 2015 by Matt T Heffron
From a C# application, how can I allocate (and free) a huge (>2GB) buffer from unmanaged memory (since I can't allocate a managed buffer >2GB) that I can pass via PInvoke to a C++ dll and then access it within the C# after the dll has filled it.The function signature of the C++ dll function...
13 Oct 2012 by Maxim Kartavenkov
Article describes how to make DirectShow Filters in .NET, it consist of BaseClasses and couple of samples
13 Oct 2012 by Maxim Kartavenkov
Article describes basic tasks for implementing your own File Source DirectShow filters.
10 Jan 2013 by Maxim Kartavenkov
Hello,You can use Marshal class and it methods PtrToStructure and StructureToPtr to convert your pDevMode IntPtr. The Unicode version of the structure DEVMODE will be:[StructLayout(LayoutKind.Explicit,CharSet=CharSet.Unicode)]public struct DEVMODEW{ ...