473,796 Members | 2,434 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DllImport, Callbacks and garbage collection

Hi.

I am trying to make this work but I got a weird behavior. I got a very
basic system, I call a unmanaged "dllimporte d" function and give it a
structure of callback functions.

Sometimes, the unmanaged part calls one of the callback functions. But
the first one has its pointer changed from its address to "0x00000001 ".
I can't figure out why.

My thought is it gets garbage collected, but I don't see why (I tried
different ways, I currently use the structure instance as static). Also
why does the garbage collector would set this to 1 instead of 0 ?

Any link or help will be appreciated :)

The code : http://www.rafb.net/paste/results/odKsGI15.html
Nov 17 '05 #1
11 3677
Hi,

If you want the garbage collector not to change your addresses use the Fixed
command on your declaration, the same happened to me using unsafe code.

Best regards
SAlva
"Fabien Penso" wrote:
Hi.

I am trying to make this work but I got a weird behavior. I got a very
basic system, I call a unmanaged "dllimporte d" function and give it a
structure of callback functions.

Sometimes, the unmanaged part calls one of the callback functions. But
the first one has its pointer changed from its address to "0x00000001 ".
I can't figure out why.

My thought is it gets garbage collected, but I don't see why (I tried
different ways, I currently use the structure instance as static). Also
why does the garbage collector would set this to 1 instead of 0 ?

Any link or help will be appreciated :)

The code : http://www.rafb.net/paste/results/odKsGI15.html

Nov 17 '05 #2
Salvador wrote:
Hi,

If you want the garbage collector not to change your addresses use the Fixed
command on your declaration, the same happened to me using unsafe code.


I am not sure it would work, "fixed" can only be used for a short amount
of time, my callbacks are called all the time until the program exits.
Also as the new address is "0x00000001 " I would rather suspect a garbage
collecting that a move of the object.
Nov 17 '05 #3
Hi,

Defenitly the Garbarge collection changes the memory address to optimize the
access and avoiding fragmentation. Also on evert collect your object will be
moved to the third generation so it can change the address at least two times
if necessary.

As you said, you can pin objects only on a method enviroment or using
stackalloc (because the stack is not under the garbage collection domain). If
you want to prevent the object to be moved on the heap you can use a managed
array, the contents of the managed array never changes because the garbage
collector will move only the position of the array but never touches the
content.

Regards
Salva

"Fabien Penso" wrote:
Salvador wrote:
Hi,

If you want the garbage collector not to change your addresses use the Fixed
command on your declaration, the same happened to me using unsafe code.


I am not sure it would work, "fixed" can only be used for a short amount
of time, my callbacks are called all the time until the program exits.
Also as the new address is "0x00000001 " I would rather suspect a garbage
collecting that a move of the object.

Nov 17 '05 #4

"Fabien Penso" <fa*********@gm ailNOSPAM.com> wrote in message
news:OY******** ******@TK2MSFTN GP12.phx.gbl...
Hi.

I am trying to make this work but I got a weird behavior. I got a very
basic system, I call a unmanaged "dllimporte d" function and give it a
structure of callback functions.

Sometimes, the unmanaged part calls one of the callback functions. But the
first one has its pointer changed from its address to "0x00000001 ". I
can't figure out why.

My thought is it gets garbage collected, but I don't see why (I tried
different ways, I currently use the structure instance as static). Also
why does the garbage collector would set this to 1 instead of 0 ?

Any link or help will be appreciated :)

The code : http://www.rafb.net/paste/results/odKsGI15.html


This can't be done, you are passing a structure containing "Delegate" types
and pretend they are function pointers in native code, which they aren't.
You have to pass the Delegate "function" pointer, this is essentially what
you do when you pass a Delegate as argument to unmanaged code like this:

public static extern void SomeNativeFunct ion(Delegate pd, ....

here the PInvoke layer does its magic and extracts the function pointer from
the Delegate and passes this pointer as argument, but you are passing a
struct and PInvoke doesn't care that each element is a Delegate.

Now, using v2.0 it's possible to get the function pointer of a delegate, but
in v1.x you can use this simple hack.

// use a msvcrt function to return a pointer from the delegate
[DllImport("msvc rt")]
public static extern IntPtr strncpy(Delegat e pd, IntPtr src, int size);

static IntPtr GetFunctionPtrF romDelegate(Del egate d)
{
// strncpy returns the buffer address (the marshaled delegate
pointer).
//We obviously don't copy anything
return strncpy(d, IntPtr.Zero, 0);
}

Usage:
1. Change your struct to hold IntPtr's

public struct phCallbacks {
public IntPtr callProgress;
...

// Call GetFunctionPtrF romDelegate passing the delegate as argument, store
the returned IntPtr in the struct.
SIPphapi.callba cksfunc.callPro gress = GetFunctionPtrF romDelegate( new
CallBackPtr(cal lProgress));
....

Hope this helps.
Willy.


Nov 17 '05 #5

"Salvador" <Sa******@discu ssions.microsof t.com> wrote in message
news:32******** *************** ***********@mic rosoft.com...
Hi,

If you want the garbage collector not to change your addresses use the
Fixed
command on your declaration, the same happened to me using unsafe code.

Best regards
SAlva


The GC has nothing to do with this see my other reply.

Willy.
Nov 17 '05 #6
Willy Denoyette [MVP] wrote:
"Fabien Penso" <fa*********@gm ailNOSPAM.com> wrote in message ...
Hope this helps.
Willy.


Hey Willy, *thanks a lot*, it does the job just fine.
Nov 17 '05 #7

"Fabien Penso" <fa*********@gm ailNOSPAM.com> wrote in message
news:eq******** ******@TK2MSFTN GP14.phx.gbl...
Willy Denoyette [MVP] wrote:
"Fabien Penso" <fa*********@gm ailNOSPAM.com> wrote in message

...

Hope this helps.
Willy.


Hey Willy, *thanks a lot*, it does the job just fine.


Great, don't forget to remove this hack when moving this code to v2.0
(search for GetFunctionPoin terForDelegate in .NET 2.0 Framework).

Willy.

Nov 17 '05 #8
As you said, you can pin objects only on a method enviroment or using
| stackalloc (because the stack is not under the garbage collection
domain). If

You can also use a GCHandle to pin an object, but as with all pinning, the
object is restricted to a basic type (int, char, arrays, etc).

| you want to prevent the object to be moved on the heap you can use a
managed
| array, the contents of the managed array never changes because the
garbage
| collector will move only the position of the array but never touches the
| content.
This is not completely accurate. The GC can (and will) move arrays (or any
other object, for that matter) allocated on the heap, unless they're pinned.

-Chris

Nov 17 '05 #9
What about just decorating the fields in the struct with

[MarshalAs(Unman agedType.Functi onPtr)]

This is available in 1.1 and 2.0. No need for hacks.

"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:u4******** ******@TK2MSFTN GP09.phx.gbl...
This can't be done, you are passing a structure containing "Delegate"
types and pretend they are function pointers in native code, which they
aren't.
You have to pass the Delegate "function" pointer, this is essentially what
you do when you pass a Delegate as argument to unmanaged code like this:

public static extern void SomeNativeFunct ion(Delegate pd, ....

here the PInvoke layer does its magic and extracts the function pointer
from the Delegate and passes this pointer as argument, but you are passing
a struct and PInvoke doesn't care that each element is a Delegate.

Now, using v2.0 it's possible to get the function pointer of a delegate,
but in v1.x you can use this simple hack.

// use a msvcrt function to return a pointer from the delegate
[DllImport("msvc rt")]
public static extern IntPtr strncpy(Delegat e pd, IntPtr src, int size);

static IntPtr GetFunctionPtrF romDelegate(Del egate d)
{
// strncpy returns the buffer address (the marshaled delegate
pointer).
//We obviously don't copy anything
return strncpy(d, IntPtr.Zero, 0);
}

Usage:
1. Change your struct to hold IntPtr's

public struct phCallbacks {
public IntPtr callProgress;
...

// Call GetFunctionPtrF romDelegate passing the delegate as argument, store
the returned IntPtr in the struct.
SIPphapi.callba cksfunc.callPro gress = GetFunctionPtrF romDelegate( new
CallBackPtr(cal lProgress));
...

Hope this helps.
Willy.

Nov 17 '05 #10

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

Similar topics

5
3247
by: Christopher Jastram | last post by:
I'm a self-taught programmer, so this might be a pretty dumb question. If it is, please point me in the right direction and I shall apologize profusely. I have a question regarding C++ and object members. Can anyone help? I'm writing a C++ wrapper for a fairly old programming interface to a document editing program that has no OOP whatsoever; only tons of structs. This program has different callbacks I'm supposed to implement for...
1
1667
by: vijaya | last post by:
I've to invoke a unmanaged dll fucntion in C# which uses a callback fucntion.The unmanaged dll fucntion returns a pointer to a structure to its callback fucntion.The user should collect those structure fields in a buffer. In my managed code(i.e. in C# program), I've used a delegate for invoking callback function and I've declared the structure too. The dll fucntion is executing finely without any errors but I'm not getting any values...
2
5118
by: Fabien Penso | last post by:
Hi. I imported a .dll in my C# code and call a C function that takes a struct of pointers of functions as callback functions. It seems to work fine (the callbacks function wrote in my C# code are called) for this part, but then crashes. When it crashes Visual offers me to use a debugger, but the current instance of visual can't be selected (only "new instance of visual C++") and if I choose "new instance" it says another debugger is...
8
3047
by: mike2036 | last post by:
For some reason it appears that garbage collection is releasing an object that I'm still using. The object is declared in a module and instantiated within a class that is in turn instantiated by the mainline. The class that instantiated the object in question is definitely still in existence at the point garbage collection swoops in and yanks it out from under my processing. Is there a way to ensure an instantiated object cannot be freed...
4
1699
by: R. MacDonald | last post by:
Hello, all, I have a .NET application (VB) that passes the address of a delegate to unmanaged code in a DLL. The unmanaged code then uses the delegate as a call-back. This seems to work fine, but now I am worried about garbage collection. I am concerned that the location of the delegate might be altered as a result of other (unused) objects being garbage collected. This would probably cause undesirable results when the unmanaged DLL...
6
14089
by: Bart Burkhardt | last post by:
Hi, I could use some help in setting a C# callback function that an external unmanaged dll will call on a event. Using a delegate and use the external callback set function doesn't work. The carbage collector says hello here (-; I have pasted some code below, any help is greatly appreciated! //Bart
56
3716
by: Johnny E. Jensen | last post by:
Hellow I'am not sure what to think about the Garbage Collector. I have a Class OutlookObject, It have two private variables. Private Microsoft.Office.Interop.Outlook.Application _Application = null; Private Microsoft.Office.Interop.Outlook.NameSpace _Namespace = null; The Constructor: public OutlookObject()
158
7909
by: pushpakulkar | last post by:
Hi all, Is garbage collection possible in C++. It doesn't come as part of language support. Is there any specific reason for the same due to the way the language is designed. Or it is discouraged due to some specific reason. If someone can give inputs on the same, it will be of great help. Regards, Pushpa
0
9680
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10455
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10173
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10006
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9052
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6788
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5441
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.