473,581 Members | 2,307 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Would C++/CLI solve PInvoke problems that C# has in this situation? What is the advantages using C++/CLI then C# when PInvoking umanaged C++ Code. Major problems here.

Hey there, this will be somewhat a long post, but any response is
appreciated!

I have done many PInvoke in the past from C++ to C#, but I did PInvoke
within C# not C++/CLI.
Can someone explain more why C++/CLI would be better to PInvoke than doing
the PInvoke in
C#?

Because, usually in C# as you already know we use DLLImport and extern
functions. Last time
when I was PInvoking a robotics library in my Lab, I had issues PInvoking an
"Asynchrono us"
method call. Before I go into that, I will explain two methods that I was
PInvoking in the past.

I already finished the .NET Wrapping and already did many helper classes to
make a .NET
framework in that library but I used a small hack which is not comfortable
but all other functions
work great except the one I am having problems.

The two methods that are similar:

deviceScheduleS ynchronous = Which polls synchronously ONCE to the device and
executes a call
back to a method that allows me to get any data I want. THIS WORKS

deviceScheduleA synchronous = Which polls asynchronously ALWAYS IN A LOOP to
the device
and executes the callback within everyloop. This keeps on running since it
spawns a new thread
whenever I execute it. This doesn't work, It crashes, Unexpected crash, with
no valid exception.

Both of the methods have the exact same parameters but different return
types:
long deviceScheduleS ynchronous (SchedulerCallb ack pCallback, void *pData,
unsigned short nPriority)
void deviceScheduleA synchronous (SchedulerCallb ack pCallback, void *pData,
unsigned short nPriority)

To make that work, I created my own Thread and loop, and used the
deviceScheduleS ynchronous to poll
the device, and it worked flawlessly.

BUT I really want to learn why deviceScheduleA synchronous didn't work. I am
wondering what
caused the not usefull, not informative exception to occur. Both
deviceScheduleS ynchronous, and
deviceScheduleA synchronous has the same parameter types, but only one of
them worked.

I was going to wrap another device, and it only had a
deviceScheduleA synchronous method, but an
exception occurs right after the first loop, once again an exception which
doesn't make sense. So I
cannot do the same hack I did before cause there is no single polling.

// C/C++ Interops Thats how it is defined
//
// typedef DeviceCallbackC ode (__stdcall *SchedulerCallb ack)(void
*pData);
// __declspec(dlli mport) unsigned long __stdcall
deviceScheduleA synchronous(Sch edulerCallback pCallback, void *pData,
unsigned short nPriority);
//
// C# PInvoke
// public delegate uint SchedulerCallba ck(object pData);
// [DllImport("robo d", EntryPoint = "#22", CharSet = CharSet.Ansi,
CallingConventi on = CallingConventi on.StdCall)]
// public static extern void
deviceScheduleA synchronous(Sch edulerCallback pCallback, IntPtr pData, ushort
nPriority);

Once again, it works for One Method, but doesn't work with the other.
Difference between the too is:
deviceScheduleS ynchronous : access Device -GrabData -Done (does this
using the current thread since its synchronous)
deviceScheduleA synchronous : start infinite loop - GrabData -GoBack
(does this in the thread since it is asynchronous)
So is it my coding problem or is it the manufacturers dll problem? I have
done this with two different manufacturers. It works
great with JAVA using JNI without any problem. Would C++/CLI solve this
issue? Should I go back in the lab and attempt it again?

Thanks!

--
Regards,
Mohamed Mansour
Microsoft Student Partner

--
Regards,
Mohamed Mansour
Microsoft Student Partner

Dec 9 '07 #1
14 3775
>Can someone explain more why C++/CLI would be better to PInvoke than doing
the PInvoke in C#?
I'd say the primary benefit is that you don't have to manually declare
all the functions you want to call, since you likely have declarations
available alreay in a header file. Incorrect declarations is a common
source of errors.

I don't know if it would help with your problem though, there's not
enough information in your post to know what goes wrong and why.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Dec 9 '07 #2
"Mohamed Mansour" <m0@community.n ospamwrote in message
news:02******** *************** ***********@mic rosoft.com...
Hey there, this will be somewhat a long post, but any response is
appreciated!

I have done many PInvoke in the past from C++ to C#, but I did PInvoke
within C# not C++/CLI.
Can someone explain more why C++/CLI would be better to PInvoke than doing
the PInvoke in
C#?

Because, usually in C# as you already know we use DLLImport and extern
functions. Last time
when I was PInvoking a robotics library in my Lab, I had issues PInvoking
an "Asynchrono us"
method call. Before I go into that, I will explain two methods that I was
PInvoking in the past.

I already finished the .NET Wrapping and already did many helper classes
to make a .NET
framework in that library but I used a small hack which is not comfortable
but all other functions
work great except the one I am having problems.

The two methods that are similar:

deviceScheduleS ynchronous = Which polls synchronously ONCE to the device
and executes a call
back to a method that allows me to get any data I want. THIS WORKS

deviceScheduleA synchronous = Which polls asynchronously ALWAYS IN A LOOP
to the device
and executes the callback within everyloop. This keeps on running since it
spawns a new thread
whenever I execute it. This doesn't work, It crashes, Unexpected crash,
with no valid exception.

Both of the methods have the exact same parameters but different return
types:
long deviceScheduleS ynchronous (SchedulerCallb ack pCallback, void *pData,
unsigned short nPriority)
void deviceScheduleA synchronous (SchedulerCallb ack pCallback, void
*pData, unsigned short nPriority)

To make that work, I created my own Thread and loop, and used the
deviceScheduleS ynchronous to poll
the device, and it worked flawlessly.

BUT I really want to learn why deviceScheduleA synchronous didn't work. I
am wondering what
caused the not usefull, not informative exception to occur. Both
deviceScheduleS ynchronous, and
deviceScheduleA synchronous has the same parameter types, but only one of
them worked.

I was going to wrap another device, and it only had a
deviceScheduleA synchronous method, but an
exception occurs right after the first loop, once again an exception which
doesn't make sense. So I
cannot do the same hack I did before cause there is no single polling.

// C/C++ Interops Thats how it is defined
//
// typedef DeviceCallbackC ode (__stdcall *SchedulerCallb ack)(void
*pData);
// __declspec(dlli mport) unsigned long __stdcall
deviceScheduleA synchronous(Sch edulerCallback pCallback, void *pData,
unsigned short nPriority);
//
// C# PInvoke
// public delegate uint SchedulerCallba ck(object pData);
// [DllImport("robo d", EntryPoint = "#22", CharSet = CharSet.Ansi,
CallingConventi on = CallingConventi on.StdCall)]
// public static extern void
deviceScheduleA synchronous(Sch edulerCallback pCallback, IntPtr pData,
ushort nPriority);

Once again, it works for One Method, but doesn't work with the other.
Difference between the too is:
deviceScheduleS ynchronous : access Device -GrabData -Done (does this
using the current thread since its synchronous)
deviceScheduleA synchronous : start infinite loop - GrabData -GoBack
(does this in the thread since it is asynchronous)
So is it my coding problem or is it the manufacturers dll problem? I have
done this with two different manufacturers. It works
great with JAVA using JNI without any problem. Would C++/CLI solve this
issue? Should I go back in the lab and attempt it again?

Thanks!

--
Regards,
Mohamed Mansour
Microsoft Student Partner

--
Regards,
Mohamed Mansour
Microsoft Student Partner

Are you sure you keep a *live* reference for your delegate instance? Note
that the JIT has no idea that a *foreign* thread might call the delegate
target asynchronously and prematurely signal to the GC that the delegate is
free to be collected.

Willy.
Willy.

Dec 9 '07 #3
>
Are you sure you keep a *live* reference for your delegate instance? Note
that the JIT has no idea that a *foreign* thread might call the delegate
target asynchronously and prematurely signal to the GC that the delegate
is free to be collected.

Wiily
Hi,

I don't know what you mean live reference ? I declare the delegate in the
same static class of the Interop Wrapper.
Your reasoning makes sense, but how do I use that reasoning in my code? How
do I make a reference to the delegate if the delegate is public and declared
inside the Interop Class.

public static class MyDevice
{
......

// Here is the delegate ... It is declared here
public delegate uint SchedulerCallba ck(IntPtr pData);

[DllImport("myde vice", EntryPoint = "#22", CharSet = CharSet.Ansi,
CallingConventi on = CallingConventi on.StdCall)]
public static extern uint
deviceScheduleA synchronous(Sch edulerCallback pCallback, IntPtr pData, ushort
nPriority);

.....
}

And I use it like the following ...

main()
{
uint deviceID = MyDevice.Init() ;
uint schedulerID = MyDevice.device Asynchronous(My DataCallback, (IntPtr)0,
MyDevice.DEFAUL T_SCHEDULER_PRI ORITY);
MyDevice.Start( );
}
private uint MyDataCallback( IntPtr data)
{
float[] pos = new float[2];
MyDevice.GetPos ition(pos);
Console.WriteLi ne("{0} {1}",pos[0],pos[1]);
}
What the above does, it turns on the device and starts it, and it will print
out the data in every iteration of the loop always asynchonously since it is
within a thread. (The C++ API)

So what do you mean live reference? The delegate is created in the same
class as a public delegate of the Interop class. Is that wrong?

Thanks for your help, any more help is appreciated.

--
Regards,
Mohamed Mansour
Microsoft Student Partner

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:eQ******** ******@TK2MSFTN GP04.phx.gbl...
"Mohamed Mansour" <m0@community.n ospamwrote in message
news:02******** *************** ***********@mic rosoft.com...
>Hey there, this will be somewhat a long post, but any response is
appreciated!

I have done many PInvoke in the past from C++ to C#, but I did PInvoke
within C# not C++/CLI.
Can someone explain more why C++/CLI would be better to PInvoke than
doing the PInvoke in
C#?

Because, usually in C# as you already know we use DLLImport and extern
functions. Last time
when I was PInvoking a robotics library in my Lab, I had issues PInvoking
an "Asynchrono us"
method call. Before I go into that, I will explain two methods that I was
PInvoking in the past.

I already finished the .NET Wrapping and already did many helper classes
to make a .NET
framework in that library but I used a small hack which is not
comfortable but all other functions
work great except the one I am having problems.

The two methods that are similar:

deviceSchedule Synchronous = Which polls synchronously ONCE to the device
and executes a call
back to a method that allows me to get any data I want. THIS WORKS

deviceSchedule Asynchronous = Which polls asynchronously ALWAYS IN A LOOP
to the device
and executes the callback within everyloop. This keeps on running since
it spawns a new thread
whenever I execute it. This doesn't work, It crashes, Unexpected crash,
with no valid exception.

Both of the methods have the exact same parameters but different return
types:
long deviceScheduleS ynchronous (SchedulerCallb ack pCallback, void
*pData, unsigned short nPriority)
void deviceScheduleA synchronous (SchedulerCallb ack pCallback, void
*pData, unsigned short nPriority)

To make that work, I created my own Thread and loop, and used the
deviceSchedule Synchronous to poll
the device, and it worked flawlessly.

BUT I really want to learn why deviceScheduleA synchronous didn't work. I
am wondering what
caused the not usefull, not informative exception to occur. Both
deviceSchedule Synchronous, and
deviceSchedule Asynchronous has the same parameter types, but only one of
them worked.

I was going to wrap another device, and it only had a
deviceSchedule Asynchronous method, but an
exception occurs right after the first loop, once again an exception
which doesn't make sense. So I
cannot do the same hack I did before cause there is no single polling.

// C/C++ Interops Thats how it is defined
//
// typedef DeviceCallbackC ode (__stdcall *SchedulerCallb ack)(void
*pData);
// __declspec(dlli mport) unsigned long __stdcall
deviceSchedule Asynchronous(Sc hedulerCallback pCallback, void *pData,
unsigned short nPriority);
//
// C# PInvoke
// public delegate uint SchedulerCallba ck(object pData);
// [DllImport("robo d", EntryPoint = "#22", CharSet = CharSet.Ansi,
CallingConvent ion = CallingConventi on.StdCall)]
// public static extern void
deviceSchedule Asynchronous(Sc hedulerCallback pCallback, IntPtr pData,
ushort nPriority);

Once again, it works for One Method, but doesn't work with the other.
Difference between the too is:
deviceScheduleS ynchronous : access Device -GrabData -Done (does this
using the current thread since its synchronous)
deviceScheduleA synchronous : start infinite loop - GrabData -GoBack
(does this in the thread since it is asynchronous)
So is it my coding problem or is it the manufacturers dll problem? I have
done this with two different manufacturers. It works
great with JAVA using JNI without any problem. Would C++/CLI solve this
issue? Should I go back in the lab and attempt it again?

Thanks!

--
Regards,
Mohamed Mansour
Microsoft Student Partner

--
Regards,
Mohamed Mansour
Microsoft Student Partner

Dec 9 '07 #4
The only reference to the delegate you have is in the call to the unmanaged
function
uint schedulerID = MyDevice.device Asynchronous(My DataCallback, (IntPtr)0,
.....
that means that after the function returns, the delegate instance (root)
becomes eligible for collection, the reason for this is that the JIT, has no
idea how the unmanaged code plans to use the instance, and signals the GC
that the object may get collected .

One way to keep the delegate instance alive [1], is by calling GC.KeepAlive,
passing the delegate reference as argument. You call this method whenever
you are sure you won't get called back by the unmanaged thread code.
[1]
main()
{
uint deviceID = MyDevice.Init() ;
// Create a delegate instance
SchedulerCallba ck scb = new SchedulerCallba ck(MyDataCallba ck);
// pass the delegate to the unmanaged function
uint schedulerID = MyDevice.device Asynchronous(sc b, (IntPtr)0,
MyDevice.DEFAUL T_SCHEDULER_PRI ORITY);
MyDevice.Start( );
// Keep the delegate instance alive for as long as you need.
GC.KeepAlive(sc b);
}

Willy.
"Mohamed Mansour" <m0@community.n ospamwrote in message
news:uC******** ******@TK2MSFTN GP05.phx.gbl...

Are you sure you keep a *live* reference for your delegate instance? Note
that the JIT has no idea that a *foreign* thread might call the delegate
target asynchronously and prematurely signal to the GC that the delegate
is free to be collected.

Wiily

Hi,

I don't know what you mean live reference ? I declare the delegate in the
same static class of the Interop Wrapper.
Your reasoning makes sense, but how do I use that reasoning in my code?
How do I make a reference to the delegate if the delegate is public and
declared inside the Interop Class.

public static class MyDevice
{
.....

// Here is the delegate ... It is declared here
public delegate uint SchedulerCallba ck(IntPtr pData);

[DllImport("myde vice", EntryPoint = "#22", CharSet = CharSet.Ansi,
CallingConventi on = CallingConventi on.StdCall)]
public static extern uint
deviceScheduleA synchronous(Sch edulerCallback pCallback, IntPtr pData,
ushort nPriority);

....
}

And I use it like the following ...

main()
{
uint deviceID = MyDevice.Init() ;
uint schedulerID = MyDevice.device Asynchronous(My DataCallback,
(IntPtr)0, MyDevice.DEFAUL T_SCHEDULER_PRI ORITY);
MyDevice.Start( );
}
private uint MyDataCallback( IntPtr data)
{
float[] pos = new float[2];
MyDevice.GetPos ition(pos);
Console.WriteLi ne("{0} {1}",pos[0],pos[1]);
}
What the above does, it turns on the device and starts it, and it will
print out the data in every iteration of the loop always asynchonously
since it is within a thread. (The C++ API)

So what do you mean live reference? The delegate is created in the same
class as a public delegate of the Interop class. Is that wrong?

Thanks for your help, any more help is appreciated.

--
Regards,
Mohamed Mansour
Microsoft Student Partner

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:eQ******** ******@TK2MSFTN GP04.phx.gbl...
>"Mohamed Mansour" <m0@community.n ospamwrote in message
news:02******* *************** ************@mi crosoft.com...
>>Hey there, this will be somewhat a long post, but any response is
appreciated !

I have done many PInvoke in the past from C++ to C#, but I did PInvoke
within C# not C++/CLI.
Can someone explain more why C++/CLI would be better to PInvoke than
doing the PInvoke in
C#?

Because, usually in C# as you already know we use DLLImport and extern
functions. Last time
when I was PInvoking a robotics library in my Lab, I had issues
PInvoking an "Asynchrono us"
method call. Before I go into that, I will explain two methods that I
was PInvoking in the past.

I already finished the .NET Wrapping and already did many helper classes
to make a .NET
framework in that library but I used a small hack which is not
comfortable but all other functions
work great except the one I am having problems.

The two methods that are similar:

deviceSchedul eSynchronous = Which polls synchronously ONCE to the device
and executes a call
back to a method that allows me to get any data I want. THIS WORKS

deviceSchedul eAsynchronous = Which polls asynchronously ALWAYS IN A LOOP
to the device
and executes the callback within everyloop. This keeps on running since
it spawns a new thread
whenever I execute it. This doesn't work, It crashes, Unexpected crash,
with no valid exception.

Both of the methods have the exact same parameters but different return
types:
long deviceScheduleS ynchronous (SchedulerCallb ack pCallback, void
*pData, unsigned short nPriority)
void deviceScheduleA synchronous (SchedulerCallb ack pCallback, void
*pData, unsigned short nPriority)

To make that work, I created my own Thread and loop, and used the
deviceSchedul eSynchronous to poll
the device, and it worked flawlessly.

BUT I really want to learn why deviceScheduleA synchronous didn't work. I
am wondering what
caused the not usefull, not informative exception to occur. Both
deviceSchedul eSynchronous, and
deviceSchedul eAsynchronous has the same parameter types, but only one
of them worked.

I was going to wrap another device, and it only had a
deviceSchedul eAsynchronous method, but an
exception occurs right after the first loop, once again an exception
which doesn't make sense. So I
cannot do the same hack I did before cause there is no single polling.

// C/C++ Interops Thats how it is defined
//
// typedef DeviceCallbackC ode (__stdcall *SchedulerCallb ack)(void
*pData);
// __declspec(dlli mport) unsigned long __stdcall
deviceSchedul eAsynchronous(S chedulerCallbac k pCallback, void *pData,
unsigned short nPriority);
//
// C# PInvoke
// public delegate uint SchedulerCallba ck(object pData);
// [DllImport("robo d", EntryPoint = "#22", CharSet = CharSet.Ansi,
CallingConven tion = CallingConventi on.StdCall)]
// public static extern void
deviceSchedul eAsynchronous(S chedulerCallbac k pCallback, IntPtr pData,
ushort nPriority);

Once again, it works for One Method, but doesn't work with the other.
Difference between the too is:
deviceScheduleS ynchronous : access Device -GrabData -Done (does
this using the current thread since its synchronous)
deviceScheduleA synchronous : start infinite loop - GrabData -GoBack
(does this in the thread since it is asynchronous)
So is it my coding problem or is it the manufacturers dll problem? I
have done this with two different manufacturers. It works
great with JAVA using JNI without any problem. Would C++/CLI solve this
issue? Should I go back in the lab and attempt it again?

Thanks!

--
Regards,
Mohamed Mansour
Microsoft Student Partner

--
Regards,
Mohamed Mansour
Microsoft Student Partner


Dec 9 '07 #5
Hi,

Thanks for your message, but I am still getting the Application to crash if
I am calling the Asynchronous Methods. I said before that When I am calling
unmanaged code asynchronous methods in C# it causes an error, if I call the
exact parameters for the synchronous method, it works fine. Cause there is
an unmanaged thread within the unmanaged method.

I was doing as you mentioned and still getting Application Crash:

// Start scheduler
HD.hdlStart();

SchedulerCallba ck cb = new
SchedulerCallba ck(HapticCallba ck);

uint temp = deviceAsynchron ous(cb, (IntPtr)0, 1);

GC.KeepAlive(ca ll);
It crashes right after the first iteration of the calback, so when I trigger
deviceAsynchron ous it creates an infinite loop that I can get data from. But
it still seems that It isn't working

Any more ideas what I have done wrong?
--
Regards,
Mohamed Mansour
Microsoft Student Partner

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:Ok******** ******@TK2MSFTN GP05.phx.gbl...
The only reference to the delegate you have is in the call to the
unmanaged function
uint schedulerID = MyDevice.device Asynchronous(My DataCallback, (IntPtr)0,
....
that means that after the function returns, the delegate instance (root)
becomes eligible for collection, the reason for this is that the JIT, has
no idea how the unmanaged code plans to use the instance, and signals the
GC that the object may get collected .

One way to keep the delegate instance alive [1], is by calling
GC.KeepAlive, passing the delegate reference as argument. You call this
method whenever you are sure you won't get called back by the unmanaged
thread code.
[1]
main()
{
uint deviceID = MyDevice.Init() ;
// Create a delegate instance
SchedulerCallba ck scb = new SchedulerCallba ck(MyDataCallba ck);
// pass the delegate to the unmanaged function
uint schedulerID = MyDevice.device Asynchronous(sc b, (IntPtr)0,
MyDevice.DEFAUL T_SCHEDULER_PRI ORITY);
MyDevice.Start( );
// Keep the delegate instance alive for as long as you need.
GC.KeepAlive(sc b);
}

Willy.
"Mohamed Mansour" <m0@community.n ospamwrote in message
news:uC******** ******@TK2MSFTN GP05.phx.gbl...
>
Are you sure you keep a *live* reference for your delegate instance?
Note that the JIT has no idea that a *foreign* thread might call the
delegate target asynchronously and prematurely signal to the GC that the
delegate is free to be collected.

Wiily

Hi,

I don't know what you mean live reference ? I declare the delegate in the
same static class of the Interop Wrapper.
Your reasoning makes sense, but how do I use that reasoning in my code?
How do I make a reference to the delegate if the delegate is public and
declared inside the Interop Class.

public static class MyDevice
{
.....

// Here is the delegate ... It is declared here
public delegate uint SchedulerCallba ck(IntPtr pData);

[DllImport("myde vice", EntryPoint = "#22", CharSet = CharSet.Ansi,
CallingConvent ion = CallingConventi on.StdCall)]
public static extern uint
deviceSchedule Asynchronous(Sc hedulerCallback pCallback, IntPtr pData,
ushort nPriority);

....
}

And I use it like the following ...

main()
{
uint deviceID = MyDevice.Init() ;
uint schedulerID = MyDevice.device Asynchronous(My DataCallback,
(IntPtr)0, MyDevice.DEFAUL T_SCHEDULER_PRI ORITY);
MyDevice.Start( );
}
private uint MyDataCallback( IntPtr data)
{
float[] pos = new float[2];
MyDevice.GetPos ition(pos);
Console.WriteLi ne("{0} {1}",pos[0],pos[1]);
}
What the above does, it turns on the device and starts it, and it will
print out the data in every iteration of the loop always asynchonously
since it is within a thread. (The C++ API)

So what do you mean live reference? The delegate is created in the same
class as a public delegate of the Interop class. Is that wrong?

Thanks for your help, any more help is appreciated.

--
Regards,
Mohamed Mansour
Microsoft Student Partner

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:eQ******* *******@TK2MSFT NGP04.phx.gbl.. .
>>"Mohamed Mansour" <m0@community.n ospamwrote in message
news:02****** *************** *************@m icrosoft.com...
Hey there, this will be somewhat a long post, but any response is
appreciate d!

I have done many PInvoke in the past from C++ to C#, but I did PInvoke
within C# not C++/CLI.
Can someone explain more why C++/CLI would be better to PInvoke than
doing the PInvoke in
C#?

Because, usually in C# as you already know we use DLLImport and extern
functions. Last time
when I was PInvoking a robotics library in my Lab, I had issues
PInvoking an "Asynchrono us"
method call. Before I go into that, I will explain two methods that I
was PInvoking in the past.

I already finished the .NET Wrapping and already did many helper
classes to make a .NET
framework in that library but I used a small hack which is not
comfortabl e but all other functions
work great except the one I am having problems.

The two methods that are similar:

deviceSchedu leSynchronous = Which polls synchronously ONCE to the
device and executes a call
back to a method that allows me to get any data I want. THIS WORKS

deviceSchedu leAsynchronous = Which polls asynchronously ALWAYS IN A
LOOP to the device
and executes the callback within everyloop. This keeps on running since
it spawns a new thread
whenever I execute it. This doesn't work, It crashes, Unexpected crash,
with no valid exception.

Both of the methods have the exact same parameters but different return
types:
long deviceScheduleS ynchronous (SchedulerCallb ack pCallback, void
*pData, unsigned short nPriority)
void deviceScheduleA synchronous (SchedulerCallb ack pCallback, void
*pData, unsigned short nPriority)

To make that work, I created my own Thread and loop, and used the
deviceSchedu leSynchronous to poll
the device, and it worked flawlessly.

BUT I really want to learn why deviceScheduleA synchronous didn't work.
I am wondering what
caused the not usefull, not informative exception to occur. Both
deviceSchedu leSynchronous, and
deviceSchedu leAsynchronous has the same parameter types, but only one
of them worked.

I was going to wrap another device, and it only had a
deviceSchedu leAsynchronous method, but an
exception occurs right after the first loop, once again an exception
which doesn't make sense. So I
cannot do the same hack I did before cause there is no single polling.

// C/C++ Interops Thats how it is defined
//
// typedef DeviceCallbackC ode (__stdcall
*SchedulerCa llback)(void *pData);
// __declspec(dlli mport) unsigned long __stdcall
deviceSchedu leAsynchronous( SchedulerCallba ck pCallback, void *pData,
unsigned short nPriority);
//
// C# PInvoke
// public delegate uint SchedulerCallba ck(object pData);
// [DllImport("robo d", EntryPoint = "#22", CharSet =
CharSet.Ansi , CallingConventi on = CallingConventi on.StdCall)]
// public static extern void
deviceSchedu leAsynchronous( SchedulerCallba ck pCallback, IntPtr pData,
ushort nPriority);

Once again, it works for One Method, but doesn't work with the other.
Difference between the too is:
deviceScheduleS ynchronous : access Device -GrabData -Done (does
this using the current thread since its synchronous)
deviceScheduleA synchronous : start infinite loop - GrabData ->
GoBack (does this in the thread since it is asynchronous)
So is it my coding problem or is it the manufacturers dll problem? I
have done this with two different manufacturers. It works
great with JAVA using JNI without any problem. Would C++/CLI solve this
issue? Should I go back in the lab and attempt it again?

Thanks!

--
Regards,
Mohamed Mansour
Microsoft Student Partner

--
Regards,
Mohamed Mansour
Microsoft Student Partner


Dec 11 '07 #6
Hi Mohamed,

Thanks for your feedback.

With the current information available, it is hard for us to say the root
cause. I also do not believe C++/CLI interop can help to resolve this
problem if the problem lies in the unmanaged side. C++/CLI uses C++ interop
technology to marshal between managed and unmanaged code and it provides
better performance than normal C# p/invoke. Also, it has the advantage of
convenient for interop.

Anyway, I think we have to find out the root cause for your crash first. I
am not sure why the exception you got did not make sense. Can you provide
the detailed stack trace of your crash? For this type of post-mortem
debugging, it is better to use windbg to get the unmanaged/managed mixed
stack trace. Please follow the steps below to obtain a stack trace for
analysis:
"How to debug application crash/hang in production environment?"
http://blogs.msdn.com/msdnts/archive...pplication-cra
sh-hang-in-production-environment.asp x

In addition to the stack trace, you may also provide the exception
information in the debugger output. Also, you may input "!gle" and
".lastevent " commands to understand the last few events before the failure.
Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Dec 11 '07 #7
Hi Jeffrey,

Since I cannot code this at home, I would have to go back to the University
Lab tomorrow and use their equipment. It is around $10,000 for the hardware.
I am doing this in my spare time to open opportunities for .NET programming
for research (I just graduated this morning from Software Engineering).

I might try another approach other than GC.KeepAlive, maybe I have to pin
the Callback since the memory space gets lost after the first loop.

But Let me rephrase my problem. The application CRASHES after access the
callback once in the Asynchronous Call. The Asynchronous method
"deviceSchedule Asynchronous" in C++ has an infinite loop which poll data
from the device. And That method is an infinite loop which is in its own
thread. All that is in the unmanaged code that the manufacturer provided.
The only thing that is visible to the consumer is :
void deviceScheduleA synchronous (SchedulerCallb ack pCallback, void
*pData,unsigned short nPriority)
long deviceScheduleS ynchronous (SchedulerCallb ack pCallback, void *pData,
unsigned short nPriority)

The C# Pinvoke are deviceScheduleA synchronous(Sch edulerCallback pCallback,
IntPtr pData, ushort nPriority); Where SchedulerCallba ck is a delegate.
Exact same for deviceScheduleS ynchronous .

deviceScheduleS ynchronous doesn't crash, but deviceScheduleA synchronous
crashes. It crashes after the first loop.

I will go back to the lab tomorrow and try the following. Maybe I have to
pin the object in the Garbage Collector like the following:

1. deviceScheduleA synchronous(Int Ptr pCallback, IntPtr pData, ushort
nPriority);
2. SchedulerCallba ck sc = new SchedulerCallba ck(MyCallBack);
3. IntPtr scPtr = GCHandle.Alloc( sc);
4. deviceScheduleA synchronous(scP tr, IntPtr.Zero, 0);

I will do a stack trace tomorrow as well.

Thanks!

--
Regards,
Mohamed Mansour
Microsoft Student Partner

""Jeffrey Tan[MSFT]"" <je***@online.m icrosoft.comwro te in message
news:tT******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hi Mohamed,

Thanks for your feedback.

With the current information available, it is hard for us to say the root
cause. I also do not believe C++/CLI interop can help to resolve this
problem if the problem lies in the unmanaged side. C++/CLI uses C++
interop
technology to marshal between managed and unmanaged code and it provides
better performance than normal C# p/invoke. Also, it has the advantage of
convenient for interop.

Anyway, I think we have to find out the root cause for your crash first. I
am not sure why the exception you got did not make sense. Can you provide
the detailed stack trace of your crash? For this type of post-mortem
debugging, it is better to use windbg to get the unmanaged/managed mixed
stack trace. Please follow the steps below to obtain a stack trace for
analysis:
"How to debug application crash/hang in production environment?"
http://blogs.msdn.com/msdnts/archive...pplication-cra
sh-hang-in-production-environment.asp x

In addition to the stack trace, you may also provide the exception
information in the debugger output. Also, you may input "!gle" and
".lastevent " commands to understand the last few events before the
failure.
Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no
rights.
Dec 11 '07 #8
"Mohamed Mansour" <m0@community.n ospamwrote in message
news:E9******** *************** ***********@mic rosoft.com...
Hi,

Thanks for your message, but I am still getting the Application to crash
if I am calling the Asynchronous Methods. I said before that When I am
calling unmanaged code asynchronous methods in C# it causes an error, if I
call the exact parameters for the synchronous method, it works fine. Cause
there is an unmanaged thread within the unmanaged method.

I was doing as you mentioned and still getting Application Crash:

// Start scheduler
HD.hdlStart();

SchedulerCallba ck cb = new
SchedulerCallba ck(HapticCallba ck);

uint temp = deviceAsynchron ous(cb, (IntPtr)0, 1);

GC.KeepAlive(ca ll);
It crashes right after the first iteration of the calback, so when I
trigger deviceAsynchron ous it creates an infinite loop that I can get data
from. But it still seems that It isn't working

Any more ideas what I have done wrong?
The KeepAlive method should have the delegate reference as argument, not
sure whether "call" is a typo but it should be "cb".

uint temp = deviceAsynchron ous(cb, (IntPtr)0, 1);
GC.KeepAlive(ca ll);

should be:

uint temp = deviceAsynchron ous(cb, (IntPtr)0, 1);
GC.KeepAlive(cb );

Also you need to keep the delegate alive for as long as you can get called
back from the unmanaged thread. In above snippet, you are only keeping the
delegate alive for the duration of the call into unmanaged, but not any
longer (which makes no sense as this is done automatically by the interop
layer)! That means that when the unmanaged thread calls you back after
KeepAlive(), the call may fail because the delegate might be collected. So
it's up to you put the KeepALive call there where you are sure you won't get
called back any longer.

Willy.

Dec 11 '07 #9

"Mohamed Mansour" <m0@community.n ospamwrote in message
news:02******** *************** ***********@mic rosoft.com...
Hey there, this will be somewhat a long post, but any response is
appreciated!

I have done many PInvoke in the past from C++ to C#, but I did PInvoke
within C# not C++/CLI.
Can someone explain more why C++/CLI would be better to PInvoke than doing
the PInvoke in
C#?
Yes, C++/CLI can help in this situation. But don't use p/invoke, it's very
clumsy and no benefit over C#. Use C++ interop instead (codename "It Just
Works").

What you want to do is define a native class with a gcroot member. The
native function can be passed as the callback, and the gcroot will keep the
managed object alive. Then in the native callback, just dereference the
gcroot and call the managed handler function.
Dec 11 '07 #10

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

Similar topics

20
3679
by: Thomas Heller | last post by:
I'm currently working on a new version of py2exe, which will require Python 2.3 and later, because it uses the zipimport mechanism. Since py2exe is a distutils extension, and since C compilers are commonly available on most platforms except Windows, it would be fairly easy to let py2exe generate a C source file installing this import hook,...
39
2793
by: Antoon Pardon | last post by:
I was wondering how people would feel if the cmp function and the __cmp__ method would be a bit more generalised. The problem now is that the cmp protocol has no way to indicate two objects are incomparable, they are not equal but neither is one less or greater than the other. So I thought that either cmp could return None in this case...
10
2392
by: BBFrost | last post by:
We just recently moved one of our major c# apps from VS Net 2002 to VS Net 2003. At first things were looking ok, now problems are starting to appear. So far ... (1) ComboBox.SelectedValue = db_value; If the db_value was not included in the ComboBox value list the ComboBox.SelectedIndex used to return -1, Now the very same code is
2
2989
by: Jeff Lederer | last post by:
I have created a simple test C# console program that calls an unmanaged C subroutine in a DLL where one of the arguments is a callback to the C# code. I noticed that when the callback has no paramaters, it works fine. But when there are parameters, I get the exception: "Runtime failure check #0: The value of ESP not properly saved..." Here...
63
4721
by: Jake Barnes | last post by:
In the course of my research I stumbled upon this article by Alex Russel and Tim Scarfe: http://www.developer-x.com/content/innerhtml/default.html The case is made that innerHTML should never be used. I'm wondering, If I wanted all the content of BODY as a string, how else could I get except through innerHTML?
4
1719
by: Peter | last post by:
Are there any restrictions in using MarshalAs when p/invoke-ing from a class library as opposed to a windows application in .NET CF 2.0? The following code will not compile in a CF class library with the error MarshalAs not found. The same code runs happily in both a Windows Applicationa and a standard class library. Is there a simple fix...
3
1702
by: Michael | last post by:
Hi all, I believe I'm not PInvoking this struct correctly. Here's the API definition. typedef struct _SP_DRVINFO_DATA { DWORD cbSize; DWORD DriverType; ULONG_PTR Reserved; TCHAR Description;
3
5735
by: Michael | last post by:
Hi all, I'm having trouble PInvoking a TCHAR within a struct. I'll paste the specific struct's API definition below. I've tried so many numerous variations. The main Win32 error I get is 0x3f0 / 515L which amounts to ERROR_NO_TOKEN. Every single instance of this in the past was due to mistakes I made while within PInvoked structs. Is...
2
2702
by: =?Utf-8?B?VG9ub2ZpdA==?= | last post by:
I've got the following umanaged code that I need to handle in C# code. The data I read comes from an external device, by Read(ID, &data, REGLEN); How should the code look for the structs in C# to handle "PULONG Value" in the function call and the "PktArray.pbyBuf = (PUCHAR)&regAddr;" "PktArray.pbyBuf = (PBYTE) pValue;" statement in C# so...
0
7868
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8149
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7899
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8175
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6553
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5674
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5364
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3805
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1403
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.