Flann C++ library has wrappers for C, C++, Python, Matlab and Ruby but no C# wrapper available. I am trying to create a C# wrapper around flann.dll 32-bit unmanaged DLL downloaded from here.
Being new to PInvoke/marshalling, I am quite certain I am not doing the C# P/Invoke calls to the DLL correctly. I am basically trying to mirror the available Python wrapper in C#. Main areas of confusion are:
I am not sure how to marshal (input) and unmarshal (output) between a 2D managed rectangular array in C# where the argument type is float* i.e. pointer to a query set stored in row major order (according to comments in flann.h).
I am also not sure how I am passing a structure reference to C is correct i.e. struct FLANNParameters*
Is IntPtr appropriate to reference typedef void* and int* indices?
Unmanaged C (flann.dll library)
Public exported C++ methods from flann.h that I need to use are as follows:
typedef void* FLANN_INDEX; /* deprecated */
typedef void* flann_index_t;
FLANN_EXPORT extern struct FLANNParameters DEFAULT_FLANN_PARAMETERS;
// dataset = pointer to a query set stored in row major order
FLANN_EXPORT flann_index_t flann_build_index(float* dataset,
int rows,
int cols,
float* speedup,
struct FLANNParameters* flann_params);
FLANN_EXPORT int flann_free_index(flann_index_t index_id,
struct FLANNParameters* flann_params);
FLANN_EXPORT int flann_find_nearest_neighbors(float* dataset,
int rows,
int cols,
float* testset,
int trows,
int* indices,
float* dists,
int nn,
struct FLANNParameters* flann_params);
Managed C# wrapper (my implementation)
Here is my C# wrapper based on the above publicly exposed methods.
NativeMethods.cs
using System;
using System.Runtime.InteropServices;
namespace FlannWrapper
{
/// <summary>
/// Methods to map between native unmanaged C++ DLL and managed C#
/// Trying to mirror: https://github.com/mariusmuja/flann/blob/master/src/cpp/flann/flann.h
/// </summary>
public class NativeMethods
{
/// <summary>
/// 32-bit flann dll obtained from from http://sourceforge.net/projects/pointclouds/files/dependencies/flann-1.7.1-vs2010-x86.exe/download
/// </summary>
public const string DllWin32 = #"C:\Program Files (x86)\flann\bin\flann.dll";
/// <summary>
/// C++: flann_index_t flann_build_index(float* dataset, int rows, int cols, float* speedup, FLANNParameters* flann_params)
/// </summary>
[DllImport(DllWin32, EntryPoint = "flann_build_index", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern IntPtr flannBuildIndex([In] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R4)] float[,] dataset, // ??? [In] IntPtr dataset ???
int rows, int cols,
ref float speedup, // ???
[In] ref FlannParameters flannParams); // ???
/// <summary>
/// C++: int flann_free_index(flann_index_t index_ptr, FLANNParameters* flann_params)
/// </summary>
[DllImport(DllWin32, EntryPoint = "flann_free_index", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int flannFreeIndex(IntPtr indexPtr, // ???
[In] ref FlannParameters flannParams); // ??? [In, MarshalAs(UnmanagedType.LPStruct)] FlannParameters flannParams);
/// <summary>
/// C++: int flann_find_nearest_neighbors_index(flann_index_t index_ptr, float* testset, int tcount, int* result, float* dists, int nn, FLANNParameters* flann_params)
/// </summary>
[DllImport(DllWin32, EntryPoint = "flann_find_nearest_neighbors_index", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int flannFindNearestNeighborsIndex(IntPtr indexPtr, // ???
[In] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R4)] float[,] testset, // ??? [In] IntPtr dataset ???
int tCount,
[Out] IntPtr result, // ??? [Out] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R4)] int[,] result,
[Out] IntPtr dists, // ???
int nn,
[In] ref FlannParameters flannParams); // ???
}
}
FlannTest.cs
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FlannWrapper
{
[TestClass]
public class FlannTest : IDisposable
{
private IntPtr curIndex;
protected FlannParameters flannParams;
// protected GCHandle gcHandle;
[TestInitialize]
public void TestInitialize()
{
this.curIndex = IntPtr.Zero;
// Initialise Flann Parameters
this.flannParams = new FlannParameters(); // use defaults
this.flannParams.algorithm = FlannAlgorithmEnum.FLANN_INDEX_KDTREE;
this.flannParams.trees = 8;
this.flannParams.logLevel = FlannLogLevelEnum.FLANN_LOG_WARN;
this.flannParams.checks = 64;
}
[TestMethod]
public void FlannNativeMethodsTestSimple()
{
int rows = 3, cols = 5;
int tCount = 2, nn = 3;
float[,] dataset2D = { { 1.0f, 1.0f, 1.0f, 2.0f, 3.0f},
{ 10.0f, 10.0f, 10.0f, 3.0f, 2.0f},
{ 100.0f, 100.0f, 2.0f, 30.0f, 1.0f} };
//IntPtr dtaasetPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(float)) * dataset2D.Length);
float[,] testset2D = { { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f},
{ 90.0f, 90.0f, 10.0f, 10.0f, 1.0f} };
//IntPtr testsetPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(float)) * testset2D.Length);
int outBufferSize = tCount * nn;
int[] result = new int[outBufferSize];
int[,] result2D = new int[tCount, nn];
IntPtr resultPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * result.Length);
float[] dists = new float[outBufferSize];
float[,] dists2D = new float[tCount, nn];
IntPtr distsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(float)) * dists.Length);
try
{
// Copy the array to unmanaged memory.
//Marshal.Copy(testset, 0, testsetPtr, testset.Length);
//Marshal.Copy(dataset, 0, datasetPtr, dataset.Length);
if (this.curIndex != IntPtr.Zero)
{
// n - number of bytes which is enough to keep any type used by function
NativeMethods.flannFreeIndex(this.curIndex, ref this.flannParams);
this.curIndex = IntPtr.Zero;
}
//GC.KeepAlive(this.curIndex); // TODO
float speedup = 0.0f; // TODO: ctype float
Console.WriteLine("Computing index.");
this.curIndex = NativeMethods.flannBuildIndex(dataset2D, rows, cols, ref speedup, ref this.flannParams);
NativeMethods.flannFindNearestNeighborsIndex(this.curIndex, testset2D, tCount, resultPtr, distsPtr, nn, ref this.flannParams);
// Copy unmanaged memory to managed arrays.
Marshal.Copy(resultPtr, result, 0, result.Length);
Marshal.Copy(distsPtr, dists, 0, dists.Length);
// Clutching straws, convert 1D to 2D??
for(int row=0; row<tCount; row++)
{
for(int col=0; col<nn; col++)
{
int buffIndex = row*nn + col;
result2D[row, col] = result[buffIndex];
dists2D[row, col] = dists[buffIndex];
}
}
}
finally
{
// Free unmanaged memory -- [BREAKPOINT HERE]
// Free input pointers
//Marshal.FreeHGlobal(testsetPtr);
//Marshal.FreeHGlobal(datasetPtr);
// Free output pointers
Marshal.FreeHGlobal(resultPtr);
Marshal.FreeHGlobal(distsPtr);
}
}
[TestCleanup]
public void TestCleanup()
{
if (this.curIndex != IntPtr.Zero)
{
NativeMethods.flannFreeIndex(this.curIndex, ref flannParams);
Marshal.FreeHGlobal(this.curIndex);
this.curIndex = IntPtr.Zero;
// gcHandle.Free();
}
}
}
}
FlannParams.cs
Trying to mirror Python FLANNParameters class and C struct FLANNParameters.
using System;
using System.Runtime.InteropServices;
namespace FlannWrapper
{
// FieldOffsets set based on assumption that C++ equivalent of int, uint, float, enum are all 4 bytes for 32-bit
[StructLayout(LayoutKind.Explicit)]
public class FLANNParameters
{
[FieldOffset(0)]
public FlannAlgorithmEnum algorithm;
[FieldOffset(4)]
public int checks;
[FieldOffset(8)]
public float eps;
[FieldOffset(12)]
public int sorted;
[FieldOffset(16)]
public int maxNeighbors;
[FieldOffset(20)]
public int cores;
[FieldOffset(24)]
public int trees;
[FieldOffset(28)]
public int leafMaxSize;
[FieldOffset(32)]
public int branching;
[FieldOffset(36)]
public int iterations;
[FieldOffset(40)]
public FlannCentersInitEnum centersInit;
[FieldOffset(44)]
public float cbIndex;
[FieldOffset(48)]
public float targetPrecision;
[FieldOffset(52)]
public float buildWeight;
[FieldOffset(56)]
public float memoryWeight;
[FieldOffset(60)]
public float sampleFraction;
[FieldOffset(64)]
public int tableNumber;
[FieldOffset(68)]
public int keySize;
[FieldOffset(72)]
public int multiProbeLevel;
[FieldOffset(76)]
public FlannLogLevelEnum logLevel;
[FieldOffset(80)]
public long randomSeed;
/// <summary>
/// Default Constructor
/// Ref https://github.com/mariusmuja/flann/blob/master/src/python/pyflann/flann_ctypes.py : _defaults
/// </summary>
public FlannParameters()
{
this.algorithm = FlannAlgorithmEnum.FLANN_INDEX_KDTREE;
this.checks = 32;
this.eps = 0.0f;
this.sorted = 1;
this.maxNeighbors = -1;
this.cores = 0;
this.trees = 1;
this.leafMaxSize = 4;
this.branching = 32;
this.iterations = 5;
this.centersInit = FlannCentersInitEnum.FLANN_CENTERS_RANDOM;
this.cbIndex = 0.5f;
this.targetPrecision = 0.9f;
this.buildWeight = 0.01f;
this.memoryWeight = 0.0f;
this.sampleFraction = 0.1f;
this.tableNumber = 12;
this.keySize = 20;
this.multiProbeLevel = 2;
this.logLevel = FlannLogLevelEnum.FLANN_LOG_WARN;
this.randomSeed = -1;
}
}
public enum FlannAlgorithmEnum : int
{
FLANN_INDEX_KDTREE = 1
}
public enum FlannCentersInitEnum : int
{
FLANN_CENTERS_RANDOM = 0
}
public enum FlannLogLevelEnum : int
{
FLANN_LOG_WARN = 3
}
}
Incorrect Output - Debug mode, Immediate Window
?result2D
{int[2, 3]}
[0, 0]: 7078010
[0, 1]: 137560165
[0, 2]: 3014708
[1, 0]: 3014704
[1, 1]: 3014704
[1, 2]: 48
?dists2D
{float[2, 3]}
[0, 0]: 2.606415E-43
[0, 1]: 6.06669328E-34
[0, 2]: 9.275506E-39
[1, 0]: 1.05612418E-38
[1, 1]: 1.01938872E-38
[1, 2]: 1.541428E-43
As you can see, I don't get any errors when running Test in Debug mode, but I know the output is definitely incorrect - garbage values as a result of improper memory addressing. I have also included alternative marshaling signatures I tried without any success (please see comments with ???).
Ground truth Python (calling PyFlann library)
To find out the correct result, I implemented a quick test using the available Python library - PyFlann.
FlannTest.py
import pyflann
import numpy as np
dataset = np.array(
[[1., 1., 1., 2., 3.],
[10., 10., 10., 3., 2.],
[100., 100., 2., 30., 1.] ])
testset = np.array(
[[1., 1., 1., 1., 1.],
[90., 90., 10., 10., 1.] ])
flann = pyflann.FLANN()
result, dists = flann.nn(dataset, testset, num_neighbors = 3,
algorithm="kdtree", trees=8, checks=64) # flann parameters
# Output
print("\nResult:")
print(result)
print("\nDists:")
print(dists)
Under the hood, PyFlann.nn() calls the publicly exposed C methods as we can tell from looking at index.py.
Correct Output
Result:
[[0 1 2]
[2 1 0]]
Dists:
[[ 5.00000000e+00 2.48000000e+02 2.04440000e+04]
[ 6.64000000e+02 1.28500000e+04 1.59910000e+04]]
Any help on the correct way to do this would be greatly appreciated. Thanks.
When you're working with p/invoke, you have to stop thinking "managed", and instead think physical binary layout, 32 vs 64 bit, etc. Also, when the called native binary always runs in-process (like here, but with COM servers it can be different) it's easier than out-of-process because you don't have to think too much about marshaling/serialization, ref vs out, etc.
Also, you don't need to tell .NET what it already knows. An array of float is an LPArray of R4, you don't have to specify it. The simpler the better.
So, first of all flann_index_t. It's defined in C as void *, so it must clearly be an IntPtr (an opaque pointer on "something").
Then, structures. Structures passed as a simple pointer in C can just be passed as a ref argument in C# if you define it as struct. If you define it as a class, don't use ref. In general I prefer using struct for C structures.
You'll have to make sure the structure is well defined. In general, you use the LayoutKind.Sequential because .NET p/invoke will pack arguments the same way that the C compiler does. So you don't have to use explicit, especially when arguments are standard (not bit things) like int, float, So you can remove all FieldOffset and use LayoutKind.Sequential if all members are properly declared... but this is not the case.
For types, like I said, you really have to think binary and ask yourself for each type you use, what's its binary layout, size? int are (with 99.9% C compilers) 32-bit. float and double are IEEE standards, so there should never be issues about them. Enums are in general based on int, but this may vary (in C and in .NET, to be able to match C). long are (with 99.0% C compilers) 32-bit, not 64-bit. So the .NET equivalent is Int32 (int), not Int64 (long).
So you should correct your FlannParameters structure and replace the long by an int. If you really want to make sure for a given struct, check Marshal.SizeOf(mystruct) against C's sizeof(mystruct) with the same C compiler than the one that was used to compile the library you're calling. They should be the same. If they're not, there's an error in the .NET definition (packing, member size, order, etc.).
Here are modified definitions and calling code that seem to work.
static void Main(string[] args)
{
int rows = 3, cols = 5;
int tCount = 2, nn = 3;
float[,] dataset2D = { { 1.0f, 1.0f, 1.0f, 2.0f, 3.0f},
{ 10.0f, 10.0f, 10.0f, 3.0f, 2.0f},
{ 100.0f, 100.0f, 2.0f, 30.0f, 1.0f} };
float[,] testset2D = { { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f},
{ 90.0f, 90.0f, 10.0f, 10.0f, 1.0f} };
var fparams = new FlannParameters();
var index = NativeMethods.flannBuildIndex(dataset2D, rows, cols, out float speedup, ref fparams);
var indices = new int[tCount, nn];
var idists = new float[tCount, nn];
NativeMethods.flannFindNearestNeighborsIndex(index, testset2D, tCount, indices, idists, nn, ref fparams);
NativeMethods.flannFreeIndex(index, ref fparams);
}
[DllImport(DllWin32, EntryPoint = "flann_build_index", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr flannBuildIndex(float[,] dataset,
int rows, int cols,
out float speedup, // out because, it's and output parameter, but ref is not a problem
ref FlannParameters flannParams);
[DllImport(DllWin32, EntryPoint = "flann_free_index", CallingConvention = CallingConvention.Cdecl)]
public static extern int flannFreeIndex(IntPtr indexPtr, ref FlannParameters flannParams);
[DllImport(DllWin32, EntryPoint = "flann_find_nearest_neighbors_index", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int flannFindNearestNeighborsIndex(IntPtr indexPtr,
float[,] testset,
int tCount,
[In, Out] int[,] result, // out because it may be changed by C side
[In, Out] float[,] dists,// out because it may be changed by C side
int nn,
ref FlannParameters flannParams);
[StructLayout(LayoutKind.Sequential)]
public struct FlannParameters
{
public FlannAlgorithmEnum algorithm;
public int checks;
public float eps;
public int sorted;
public int maxNeighbors;
public int cores;
public int trees;
public int leafMaxSize;
public int branching;
public int iterations;
public FlannCentersInitEnum centersInit;
public float cbIndex;
public float targetPrecision;
public float buildWeight;
public float memoryWeight;
public float sampleFraction;
public int tableNumber;
public int keySize;
public int multiProbeLevel;
public FlannLogLevelEnum logLevel;
public int randomSeed;
}
note: I've tried to use the specific flann parameters values, but the library crashes in this case, I don't know why...
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;
Console.Write(a);
Console.ForegroundColor = c;
}
So when a new block comes/i want to move somehing:
writeCol(blokk, ConsoleColor.Magenta);
Where blokk is:
private const string blokk = "█";
I have found a way to "write" to the console faster:
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace ConsoleApplication1
{
class Program
{
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern SafeFileHandle CreateFile(
string fileName,
[MarshalAs(UnmanagedType.U4)] uint fileAccess,
[MarshalAs(UnmanagedType.U4)] uint fileShare,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] int flags,
IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteConsoleOutput(
SafeFileHandle hConsoleOutput,
CharInfo[] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpWriteRegion);
[StructLayout(LayoutKind.Sequential)]
public struct Coord
{
public short X;
public short Y;
public Coord(short X, short Y)
{
this.X = X;
this.Y = Y;
}
};
[StructLayout(LayoutKind.Explicit)]
public struct CharUnion
{
[FieldOffset(0)] public char UnicodeChar;
[FieldOffset(0)] public byte AsciiChar;
}
[StructLayout(LayoutKind.Explicit)]
public struct CharInfo
{
[FieldOffset(0)] public CharUnion Char;
[FieldOffset(2)] public short Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct SmallRect
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}
[STAThread]
static void Main(string[] args)
{
SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
if (!h.IsInvalid)
{
CharInfo[] buf = new CharInfo[80 * 25];
SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };
for (byte character = 65; character < 65 + 26; ++character)
{
for (short attribute = 0; attribute < 15; ++attribute)
{
for (int i = 0; i < buf.Length; ++i)
{
buf[i].Attributes = attribute;
buf[i].Char.AsciiChar = character;
}
bool b = WriteConsoleOutput(h, buf,
new Coord() { X = 80, Y = 25 },
new Coord() { X = 0, Y = 0 },
ref rect);
}
}
}
Console.ReadKey();
}
}
}
(This code prints out all the characters from A-Z).
So finnaly the question:
How can i modify this code to take advantage of it?
Thanks in advance. Have a nice day.
EDIT:
I found 1 way but it gives me buggy text. Any ideas?
public static void Writetocol(string s)
{
var kiir = s;
byte[] barr;
kiir = Convert.ToString(kiir);
barr = Encoding.ASCII.GetBytes(kiir);
SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
if (!h.IsInvalid)
{
CharInfo[] buf = new CharInfo[80 * 25];
SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };
for (short attribute = 0; attribute < 15; ++attribute)
{
for (int i = 0; i < barr.Length; ++i)
{
buf[i].Attributes = attribute;
buf[i].Char.AsciiChar = barr[i];
}
bool b = WriteConsoleOutput(h, buf,
new Coord() { X = 80, Y = 25 },
new Coord() { X = 0, Y = 0 },
ref rect);
}
}
}
It gives me this:
When it should give me this:
(It's written Hungarian if anyone wonders)
You could parse the string you provide to fill the buffer by handling your own linefeeds and position, like so:
static void writeCol(string a, ConsoleColor b)
{
byte x = 0, y = 0;
// parsing to make it fly
// fill the buffer with the string
for(int ci=0; ci<a.Length;ci++)
{
switch (a[ci])
{
case '\n': // newline char, move to next line, aka y=y+1
y++;
break;
case '\r': // carriage return, aka back to start of line
x = 0;
break;
case ' ': // a space, move the cursor to the right
x++;
break;
default:
// calculate where we should be in the buffer
int i = y * 80 + x;
// color
buf[i].Attributes= (short) b;
// put the current char from the string in the buffer
buf[i].Char.AsciiChar = (byte) a[ci];
x++;
break;
}
}
// we handled our string, let's write the whole screen at once
bool success = WriteConsoleOutput(h, buf,
new Coord() { X = 80, Y = 25 },
new Coord() { X = 0, Y = 0 },
ref rect);
}
Notice that I already refactored the safehandle h and the native buffer buf to the static state so we only have this once in the app:
static IntPtr h= GetStdHandle(STD_OUTPUT_HANDLE);
static CharInfo[] buf = new CharInfo[80 * 25];
static SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };
I have added the GetStdHandle
//http://www.pinvoke.net/default.aspx/kernel32/GetStdHandle.html
const int STD_OUTPUT_HANDLE = -11;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
You need to change the method signature on WriteConsoleOutput to accept an IntPtr instead of SafeFileHandle in that case.
I tested this method with the following test call:
writeCol(#"
TEST
======
1 test
FuBar", ConsoleColor.Blue);
which gives this result:
So keep in mind to fill the buffer buf at the correct positions first and then call WriteConsoleOutput to copy the buffer to the screen at once. If you call that very often you are back to square one...
Notice that you don't need to write the whole screen. By using different rectangles you can write only parts of the screen.
For this demo I left out all error-checking. That is up to you to check.
You might want to read up on the native calls used from the msdn documentation
So I have a library with lots of C style functions described as:
/// Finds the polygon nearest to the specified center point.
/// #param[in] center The center of the search box. [(x, y, z)]
/// #param[in] extents The search distance along each axis. [(x, y, z)]
/// #param[in] filter The polygon filter to apply to the query.
/// #param[out] nearestRef The reference id of the nearest polygon.
/// #param[out] nearestPt The nearest point on the polygon. [opt] [(x, y, z)]
/// #returns The status flags for the query.
dtStatus findNearestPoly(const float* center, const float* extents,
const dtQueryFilter* filter,
dtPolyRef* nearestRef, float* nearestPt) const;
I wonder how shall I wrap tham in my CLI wrapper to make callable from C#? Here my main intrest is const float* center which is [(x, y, z)] pointer - how to form such in C#, how to get tham out in C#? So in general how to work with float* in CLI code to make it avaliable in C# code (in and out)?
Following up on the two other answers, here's what some actual code may look like
Poly.cpp (C++/CLI)
#include "stdafx.h"
#include "Poly.h"
#include "findNearestPoly.h"
using namespace System;
namespace CStyleArrays
{
public ref class Poly abstract sealed // "abstract sealed" = static
{
public:
static int FindNearest(Tuple<float, float, float>^ center, Tuple<float, float, float>^ extents,
[Runtime::InteropServices::Out] Tuple<float, float, float>^% nearestPt) {
const float pCenter[] = { center->Item1, center->Item2, center->Item3};
const float pExtents[] = { extents->Item1, extents->Item2, extents->Item3};
float pNearestPt[3];
int retval = findNearestPoly(pCenter, pExtents, nullptr /*filter*/, nullptr /*nearestRef*/, pNearestPt);
// if (retval == success)
{
nearestPt = Tuple::Create(pNearestPt[0], pNearestPt[1], pNearestPt[2]);
}
return retval;
}
static int FindNearest(cli::array<float>^ center, cli::array<float>^ extents, cli::array<float>^% nearestPt) {
if ((center->Length != 3) || (extents->Length != 3) || (nearestPt->Length != 3))
throw gcnew ArgumentOutOfRangeException();
const pin_ptr<float> pinCenter = ¢er[0]; // "... if any element of an array is pinned, then the whole array is also pinned ..."
const float* pCenter = pinCenter;
const pin_ptr<float> pinExtents = &extents[0];
const float* pExtents = pinExtents;
const pin_ptr<float> pinNearestPt = &nearestPt[0];
float* pNearestPt = pinNearestPt;
return findNearestPoly(pCenter, pExtents, nullptr /*filter*/, nullptr /*nearestRef*/, pNearestPt);
}
};
}
Sample C# would be
namespace TestCStyleArrays
{
class Program
{
static void Main(string[] args)
{
{
var center = Tuple.Create(0f, 1f, 2f);
var extents = Tuple.Create(10f, 20f, 30f);
Tuple<float, float, float> nearestPt;
CStyleArrays.Poly.FindNearest(center, extents, out nearestPt);
}
{
var center = new[] { 0f, 1f, 2f };
var extents = new[] { 10f, 20f, 30f };
var nearestPt = new float[3];
CStyleArrays.Poly.FindNearest(center, extents, ref nearestPt);
}
}
}
}
to add to #Serious's post, the example function prototype may be:
dtStatus findNearestPoly(array<float> ^center,
array<float> ^extents,
array<dtQueryFilter> ^filter,
[out] dtPolyRef %nearestRef,
[out] array<float> ^%nearestPt) const;
for this example, I'm assuming that dtQueryFilter, dtStatus and dtPolyRef are enums or some other directly passable type. If they are classes, then a suitable ref class will need to be created, and the references will include the ^ pointer.
Then, to use the arrays data, you will need to use the pin_ptr to lock them from GC:
pin_ptr<float> ppf = ¢er[0];
float *pCenter = ppf;
Note, to use the [out] parameter you will have to:
using namespace System::Runtime::InteropServices;
Either use a simple cli::array<float> or a Tuple<float,float,float>: http://msdn.microsoft.com/en-us/library/dd383822.aspx
Tuple is defined in the mscorlib assembly so in both cases you won't pull any additional dependencies.
When I do this;
Point startpoint = Cursor.Position;
startpoint.Y -= 1;
DoMouse(MOUSEEVENTF.MOVE | MOUSEEVENTF.ABSOLUTE, startpoint);
The mouse doesn't just move up.. it moves a bit to the left as well. But if I do it in a loop, it only moves to the left at the first iteration.
Here is a fully working console program presenting the problem. You have to Add Reference -> .NET -> System.Drawing and System.Windows.Forms to get it to compile.
When starting the program type start to move the mouse up 5 pixels once or type start X (X being a number) to move the mouse up 5 pixels X times. You will see that each new loop the mouse will move a bit to the left; it shouldn't be doing that at all.
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace mousemove_temp
{
class Program
{
//Capture user input
static void Main(string[] args)
{
while (true)
{
string s = Console.ReadLine();
switch (s)
{
case("start"):
moveMouseTest(1);
break;
default:
//Get # of times to run function
Match match = Regex.Match(s, #"start (.+)", RegexOptions.IgnoreCase);
if (!match.Success || match.Groups.Count != 2) break;
//Copy # to int
int amnt = -1;
try
{
amnt = Int32.Parse(match.Groups[1].Value);
}
catch (Exception) { break; } //fail
if (amnt <= -1) break; //fail
moveMouseTest(amnt); //aaaawww yeah
break;
}
Thread.Sleep(10);
}
}
//Move the mouse
static void moveMouseTest(int repeat)
{
int countrepeat = 0;
//Loop entire function X times
while (countrepeat < repeat)
{
Point startpoint = Cursor.Position;
int amount = 5; //Move 5 pixels
int counter = 0;
//Move 1 pixel up each loop
while (counter < amount)
{
startpoint.Y -= 1;
DoMouse(MOUSEEVENTF.MOVE | MOUSEEVENTF.ABSOLUTE, startpoint);
counter++;
Thread.Sleep(100); //Slow down so you can see it only jumps left the first time
}
countrepeat++;
Console.WriteLine(String.Format("{0}/{1}", countrepeat, repeat));
Thread.Sleep(1000); //Wait a second before next loop
}
}
/*
* Function stuff
*/
//Control the Mouse
private static object mouselock = new object(); //For use with multithreading
public static void DoMouse(MOUSEEVENTF flags, Point newPoint)
{
lock (mouselock)
{
INPUT input = new INPUT();
MOUSEINPUT mi = new MOUSEINPUT();
input.dwType = InputType.Mouse;
input.mi = mi;
input.mi.dwExtraInfo = IntPtr.Zero;
// mouse co-ords: top left is (0,0), bottom right is (65535, 65535)
// convert screen co-ord to mouse co-ords...
input.mi.dx = newPoint.X * (65535 / Screen.PrimaryScreen.Bounds.Width);
input.mi.dy = newPoint.Y * (65535 / Screen.PrimaryScreen.Bounds.Height);
input.mi.time = 0;
input.mi.mouseData = 0;
// can be used for WHEEL event see msdn
input.mi.dwFlags = flags;
int cbSize = Marshal.SizeOf(typeof(INPUT));
int result = SendInput(1, ref input, cbSize);
if (result == 0)
Console.WriteLine("DoMouse Error:" + Marshal.GetLastWin32Error());
}
}
/*
* Native Methods
*/
[DllImport("user32.dll", SetLastError = true)]
static internal extern Int32 SendInput(Int32 cInputs, ref INPUT pInputs, Int32 cbSize);
[DllImport("user32.dll")]
public static extern bool GetAsyncKeyState(Int32 vKey);
[StructLayout(LayoutKind.Explicit, Pack = 1, Size = 28)]
internal struct INPUT
{
[FieldOffset(0)]
public InputType dwType;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct MOUSEINPUT
{
public Int32 dx;
public Int32 dy;
public Int32 mouseData;
public MOUSEEVENTF dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct KEYBDINPUT
{
public Int16 wVk;
public Int16 wScan;
public KEYEVENTF dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct HARDWAREINPUT
{
public Int32 uMsg;
public Int16 wParamL;
public Int16 wParamH;
}
internal enum InputType : int
{
Mouse = 0,
Keyboard = 1,
Hardware = 2
}
[Flags()]
internal enum MOUSEEVENTF : int
{
MOVE = 0x1,
LEFTDOWN = 0x2,
LEFTUP = 0x4,
RIGHTDOWN = 0x8,
RIGHTUP = 0x10,
MIDDLEDOWN = 0x20,
MIDDLEUP = 0x40,
XDOWN = 0x80,
XUP = 0x100,
VIRTUALDESK = 0x400,
WHEEL = 0x800,
ABSOLUTE = 0x8000
}
[Flags()]
internal enum KEYEVENTF : int
{
EXTENDEDKEY = 1,
KEYUP = 2,
UNICODE = 4,
SCANCODE = 8
}
}
}
Can anybody tell what's going wrong?
You're doing the math wrong and as a result are getting rounding errors.
For example, 65535 / 1920 = 34.1328125. But truncation (because you are dividing an int by an int) is resulting in 34. So if on a 1920x1080 screen you had the mouse all the way at the right, you would get 1920 * (65535 / 1920) = 1920 * 34 = 65280.
This will get you better results:
input.mi.dx = (int)((65535.0f * (newPoint.X / (float)Screen.PrimaryScreen.Bounds.Width)) + 0.5f);
input.mi.dy = (int)((65535.0f * (newPoint.Y / (float)Screen.PrimaryScreen.Bounds.Height)) + 0.5f);
Though if you're determined to use P/Invoke rather than just say
Cursor.Position = new Point(newPoint.X, newPoint.Y);
then you really should use SetCursorPos - http://msdn.microsoft.com/en-us/library/windows/desktop/ms648394(v=vs.85).aspx - since that (along with GetCursorPos) is the API that .NET is using to get and set the cursor position via Cursor.Position.
Simplest way for your project is useful open-source library Windows Input Simulator (C# SendInput Wrapper - Simulate Keyboard and Mouse) on codeplex. Use it!