Skip to main content
gamedev.net
🔒 Locked

c# calling windows api function

Started by RunningInt 0 replies 500+ views
Original Post
RunningInt
RunningInt
Hi, I am trying to call the winapi function GetCursorPos from C#


[DllImport("user32.dll"),CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall]
public static extern int GetCursorPos(ref POINTL lpPoint);

[StructLayout(LayoutKind.Sequential)] 
public class POINTL
{
   public int x;
   public int y;
}

...

public POINTL test()
{
    POINTL p = new POINTL();
    GetCursorPos(ref p);
    return p.x;
}




However it throws a NullReferenceException, claiming that the "object reference has not been set to an instance of an object" (shouldn't that be instance of a class?) I largely followed a tutorial doing something very similar found here And cannot figure out what I am doing wrong.
Arild Fines
Arild Fines
Make POINTL a struct, not a class. Instances of classes will be created on the managed heap, and you have no real control over what the layout will be (despite the LayoutKind attribute). A ref to a reference to a class instance will not point anywhere meaningful. Structs on the other hand are created on the stack, and a ref to it will be the actual address of the struct instance.
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.