473,434 Members | 1,791 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,434 software developers and data experts.

Callback with unsafe double* to double[] Problem :

I am using a DLL written in C, it uses some pointers on functions, I
have defined a wrapper around it in C# which uses some delegates:

#region Delegates and Marshalling to call solvopt

public delegate double funCallback(double[] x);
public delegate double funcCallback(double[] x);
public delegate void gradCallback(double[] x, double[] v);
public delegate void gradcCallback(double[] x, double[] v);

[DllImport("SolvOpt_C.dll")] //, EntryPoint="useFunc")]
extern static unsafe double* solvopt(UInt16 n, double[] x, funCallback
fun, gradCallback grad, double[] options, funcCallback func,
funcCallback gradc);
public static unsafe double[] SolvOptWrapper(UInt16 n, double[] x,
funCallback fun, gradCallback grad, double[] options, funcCallback
func, funcCallback gradc)
{
double* us_Ret;
double[] retVal = new double[n + 1];
int it = 0;

us_Ret = solvopt(n, x, fun, grad, options, func, gradc);

retVal.Initialize();
for ( it = 0 ; it < n+1 ; ++it )
retVal[it] = us_Ret[it];
return retVal;
}
#endregion

static unsafe double funTest(double[] x)
{
return ( Math.Sqrt(x[0] - 4) + Math.Sqrt(x[1] - 3));
}

public static void TestDelegates()
{
UInt16 n;
double[] x;
funCallback fun = new funCallback(funTest);
gradCallback grad = null;
funcCallback func = null;
funcCallback gradc = null;
double[] solvopt_options = new double[13]{-1.0e+0 , 1.0e-4 , 1.0e-6 ,
15.0e+3 , 0.0e+0,1.0e-8 , 2.5e+0 , 1.0e-11 , 0.0e+0 , 0.0e+0 , 0.0e+0 ,
0.0e+0 , 0.0e+0};

n = 2;
x = new double[2]{ 2.0 , 1.0 };

SolvOptWrapper(n, x, fun, grad, solvopt_options, func, gradc);
}

When I call TestDelegate I get this error:

An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in ConsoleTester.exe

Additional information: Index was outside the bounds of the array.

From what I understand the debugger is telling me that the double[2]

that I pass in parameter is converted to a double* when calling the C
function.

However when the C function (solvopt) calls the Callback function by
the delegate (funTest) the parameter is passed as double[1], probably
because it has no idea about the length of the array.

Anybody knows how I can solve this problem knowing that I cannot know
the size of this array before the function is called (the size is the
UInt16 n).

Cheers
Anthony

Apr 21 '06 #1
3 2858
I found a rather inelegant solution:

- first of all make usre that you use __stdcall option by default for
the C project or the callback function will create an ESP problem.
- instead of using double[], declare it as unsafe and use IntPtr
- convert the IntPtr to a void* using to ToPointer and recast it in
double*
- then iterate the pointer using []

The changes are like the following lines:

public delegate double funCallback(IntPtr x);
public delegate double funcCallback(IntPtr x);

static unsafe double funTest(IntPtr ptr)
{
double* x = (double*)ptr.ToPointer(); // oops ! really dirty cast
Console.WriteLine("x[0] = " + x[0].ToString() + "x[1] = " +
x[1].ToString() + " --> " +(x[0] - 4) * (x[0] - 4) + (x[1] - 3) * (x[1]
- 3) );
return ( (x[0] - 4) * (x[0] - 4) + (x[1] - 3) * (x[1] - 3) );
}

If you know a better solution that would make the callbacks not
declared as unsafe please let me know !

Cheers
Anthony N.

Apr 21 '06 #2
> - first of all make usre that you use __stdcall option by default for
the C project or the callback function will create an ESP problem.


Does that mean you can modify the C code? If so, changing the callback
signature to include the array size as a separate parameter would
help.

Otherwise if you want to avoid using unsafe in the funTest method (and
I don't quite see why since you're already using unsafe code in
SolvOptWrapper) I think you have to use copy the data from the array
and back with Marshal.Copy().
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Apr 21 '06 #3
Good point, at first I didn't have access to the C code :)

I would like to use unsafe in funTest since the SolvOptWrapper is
supposed to be an interface to the DLL, the classes which will use this
interface will have to define their own funTest method Callback to call
SolvOptWrapper. So it would force the people who will use the interface
to define unsafe methods for each class which will use the wrapper

Thanks for the insight !
Anthony N.

Apr 22 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: vijaya | last post by:
I've to invoke a unmanaged dll fucntion in C# which uses a callback fucntion.The unmanaged dll fucntion is as follows **************************************** The Original Fucntion in the dll...
3
by: Jim | last post by:
I have a windows application that is accessing unmanaged code and providing a callback function that will create events at unknown time spans. When the EventHandler (callback function) fires it...
2
by: Jannis Linxweiler | last post by:
Hi NG! I have a problem with my unsafe code. I'd like to get a pointer on a jagged array like this: double arr = new double; for (int i....); arr = new double;
7
by: SB | last post by:
What is the proper way to pass a character array (char *) from a "C" dll to a C# method (delegate) in my app? Getting the dll (which simulates a third party dll) to call my delegate works fine. ...
0
by: Lutz Niggl | last post by:
I register a callback function to an external dll. The callback function has the following signature: void Callback(DWORD action, DWORD buffersize, DWORD buffer) The callback is supposed to...
7
by: Rich Claxton | last post by:
Hi we have a 3rd party in process com dll, which was written In C++ and our client is in c#. All is working fine apart from we get a callback from the DLL which contains an array of structures....
8
by: Lars Schouw | last post by:
Guys, Is there anyway in C++ to setup a callback for a member function that takes two arguments I am trying to use boost::function but that only works with std::bind1st that does only take one...
5
by: greg.merideth | last post by:
I have a class that I've provided an event for to be called when the processing in the class is complete (a callback). The class spins up a series of threads for the background operation and I'm...
12
by: Darwin Lalo | last post by:
I have a lot of code like this: VOID CALLBACK TimerRoutine(PVOID lpParam) { long nTaskid = (long)lpParam; GObj *obj; if( mapThreadSafe.find( nTaskid, obj )) // mapThreadSafe is a hash_map,...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.