Delegates in SWIG - C# - c#

( complete duplicate of http://old.nabble.com/C%2B%2B-pointer-to-method-as-parameter-to-C--td17645155.html , but couldn't make the proposed macro work)
I've got the following C++ function (simplified) :
InputPort addInputPort(void(*callback)(InputPort));
Problem : the signature of the generated C# function is :
public InputPort addInputPort(SWIGTYPE_p_f__InputPort____void callback)
SWIGTYPE_p_f__InputPort____void is not a delegate (and has no public constructor anyway), so I can't use addInputPort.
How do I tell SWIG to use a delegate instead ? If the solution involves %typemap, please be extra patient with me...

The solution involves a %typemap. The effect you are seeing is the default useless mapping for unknown types. In your case, the unknown type is the function type void *(InputPort).
In fact, all of SWIG's translation is based on %typemaps which have already been written and live in standard SWIG libraries. You can investigate the initial %typemaps for C# in this Subversion location.
In particular, look for SWIGStringHelper in csharphead.swg. That code maps a delegate to a C callback. The trick is to add a helper callback implementation in the SWIG module.

Related

Using bound interface in F#

I am trying to use C# library in F# so it would be very much specific case. I using Servicestack with F#. Now, I am trying to wire up class with interface using method
RegisterAutoWiredAs<T,'TAs>()
signature. Here is 'T is having constraint that it has to implement 'TAs. It works fine in C# code.
But F# is having constraint while using interface.
let f:IFoo = Foo() // will give type error
let fi:IFoo - Foo() :> IFoo // will work
Here Foo has implemented IFoo. So, this part is quite different than C# equivalent. Now, above signature is giving type error if I do like this
container.RegisterAutoWiredAs<Foo,IFoo>()
And there is noway to do casting while giving parameter.
Here is line from original project I am trying to run. Everything in this code works other than this part and also sadly other equivalent methods are also failing.
And here is the error I am getting in that project
This expression was expected to have type
'MemoryChatHistory' but here has type
'IChatHistory'
F# does not support implicit interface implementations.
I think you may be able to work around this in this instance by making IChatHistory an abstract class rather than an interface (using [<AbstractClass>] attribute).
EDIT:
Nope, I had a chance to play around with it today. I think it's impossible to call this method directly with those type parameters from F#. See this question
How do I translate a `where T : U` generic type parameter constraint from C# to F#?
for a little more discussion.
You might be able to work around this by using reflection to call the method.

What does the syntax seen when decompiling c# dynamic operations actually mean?

I've recently had to make a forray into decompiling a colleague's code while they're away, and found that most of it looks surprisingly nice (thanks ILSpy), with the notable exception of a couple of places where we needed to use dynamic - these got mangled into several parts:
A call site container - i.e. what resembles a class in definition, but let's say the method in which dynamic was used was DoStuff, would have a declaration along the lines of public /* static? I forget */ class <DoStuff>CallSiteContainer_Plus_Some_Weirdness { /* bunch of CallSite fields */ }
A lot of code that checks whether various CallSites within the container have been assigned and assigns them before usage as required using approaches I really don't get yet.
My question is regarding the syntax of the class declaration in the 1st point. It looks like a generic class, but it clearly isn't. Can anyone explain what's going on there?
Please note, I'm not looking for help in working out the original code - I've already managed to do that by judicious use of find and replace, and breaking out the autogenerated code from everything else. But I'd like to understand how the CallSite container syntax is a valid class name!
Here's an example of such auto-generated class:
private static class <>o__0
{
public static CallSite<Action<CallSite, Type, object>> <>p__0;
}
If you are worried about the <>o__0 class name and the <>p__0 field name, then you are right, those are not valid C# names but this doesn't mean that they are not valid IL names which is what the compiler generates. The reason why it uses such special symbols is to ensure that they will never conflict with class names that you as a developer might have written.

Interop with another function in a different class

I would have to call C++ code from .Net code via interop.
I just wonder whether is there anyway to interop with another function in a different class? For example, in C++, I have the following utility class:
class ConvertUtility
{
public:
static void Convert(PointList &ptList, const list<pts> &pts);
};
I wish to call it directly from .Net via interop, any idea how to do this?
Note: here's a related question asking about how to use namespace to distinguish between different method. But this time, I want nothing to do with namespace, only a class with static function.
Edit: Given that there are already too many functions in the C wrapper ( e.g, static extern "C" function that are callable from .Net, without class or namespace), I won't want to introduce an extra layer of wrapping, if I can help it.
In the related question you linked to, Ben Voigt says in a comment to the suggestion to write a C++/CLI wrapper:
This IS the correct answer. P/Invoke should only be used to call
functions with a "C" interface, which means extern "C" to prevent name
mangling, and also restrictions on parameter and return types.
Since the method is static, I see two options:
Write a simple C wrapper function that can be called with P/Invoke.
Write a C++/CLI wrapper that can be called directly from C#.

Delegates in objective c

First I should tell you that ive little knowledge of Objective C or C#.So when one of my collegues asked me whether there is anything like delegates in Objective C,I wondered if such a concept existed in Objective-C.I guess the delegates we use in iphone programing are not the same.C# delegates are function pointers right? Such a facility would be nice to have while working with multiple views.Where can i find info??
Delegates in Objective-C are merely a concept, not some kind of implementation artifact (like in C#). A delegate in Objective-C (better: Cocoa) is basically an object, which is notified by whoever uses it as its "delegate" of certain events occuring. Delegates may also be asked to perform certain tasks on behalf of the host object. The interface a delegate is required to implement is often formalized by a protocol.
#protocol ActionDelegate
- (void) actionDidStart: (id) aSender;
- (void) actionDidEnd: (id) aSender;
#end
#interface Action: NSObject {
id<ActionDelegate> delegate;
}
#property (nonatomic,assign) id<ActionDelegate> delegate;
#end
Delegates in C#, on the other hand, are an implementation artifact. There is a dedicated delegate keyword to declare delegate types and to create actual delegate instances.
class Action {
delegate void ActionDidStartDelegate(Action sender);
delegate void ActionDidEndDelegate(Action sender);
...
}
(my C# is a bit rusty, so the syntax may be off here, sorry; and in real life, one would probably use events in situations like the above rather than raw delegates). Basically, a C# delegate is akin to a Python method object.
You might be able to use the new code block feature of Objective-C to emulate delegates. Not having used this feature (yet), I cannot comment on this. Another way to get something like that would be to use plain function pointers.
typedef void (*callback_function)();
- (void) doSomethingWithCallback: (callback_function) func {
...
func();
}
And of course, you can always use the method often employed by Cocoa itself: use an object and an associated method selector:
- (void) doSomethingWhenDonePerform: (SEL)aSelector onObject: (id) aReceiver {
...
[aReceiver perform: aSelector];
}
C# delegates are something like NSInvocations in Objective-C:
each knows the object that will be the target of the call
each knows the method that will be called
however, an NSInvocation goes further:
it knows the arguments to pass to the method
it can store the return value
You probably wouldn't use NSInvocation to implement a pattern like C# delegates (which are a form of Proxy pattern). Personally I'd choose to use an object that forwards messages it receives to the target object, using the standard message-forwarding features of the runtime.

Exposing C# struct to COM breaks for VB6 app

Last Updated: 2009-08-11 2:30pm EDT
A few days ago I posted this question about some very strange problems. Well, I figured out what specifically was causing a build on one machine to not run on others and even came up with a work-around, but now it leaves me with a nice, specific question: Why?
To reproduce the problem, I create a new InteropUserControl and do the following:
Add a new public struct MyStruct:
Give it a GUID and ComVisible attributes
Add a GetMyStruct member to the _InteropUserControl interface and implement it in InteropUserControl.
MyStruct:
[Guid("49E803EC-BED9-4a08-B42B-E0499864A169")]
[ComVisible(true)]
public struct MyStruct {
public int mynumber;
}
_InteropUserControl.GetMyStruct():
[DispId(7)]
void getMyStruct( int num, ref MyStruct data );
(I have tried returning MyStruct instead of passing by reference, as well.)
InteropUserControl.GetMyStruct() implementation:
public void getMyStruct( int num, ref MyStruct data ) {
data = new MyStruct();
data.mynumber = num * 2;
}
I also sign the assembly and install it to the GAC and register with Regasm. Upon adding it to a new VB6 project and adding a call to GetMyStruct() and compiling on our build machine, it refuses to run on other machines.
To get around this, I had to expose a class to COM instead of the struct, and basically change GetMyStruct to this:
public void GetMyData( int num, MyClass data ) {
data.mynumber = num * 2;
}
In my actual project, I retrieve the struct internally, and then copy all the field values from the struct to the matching members on the instance of the class passed to the method by the client.
So why did a struct cause this behavior and a class worked fine? Is there some magic to exposing a struct to COM for using in VB6?
I think it may have something to do with OLE Automation.
Note: I also tried returning the struct rather than using a ref parameter, but that did not change the behavior.
Edit to add link to project template:
Interop Forms Toolkit 2.0 is the original VB.NET project template and dll. I don't reference the dll, so you may not need to install this.
C# Translations of templates on CodeProject is what I used to create mine (the project template, not the item template). The VB.NET version generates the __InteropUserControl event interface, the _InteropUserControl interface, and a few relevant attributes automagically. Those are explicitly coded in the C# version, and that's about all that's different between the two.
I think I found a solution to this problem.
I had the same exact problem, vb6 breaks when calling a method of an interop library by passing an structure. This is a project I created for testing a DLL interop, so all I have in my project was a form. But I had another project (the main application) with the same reference and it works fine.
After reading Joel post, I wanted to test his solution and in fact id did work (using a class instead a structure). But I have other interops where I'm using structures, so I was quite worried that at any point my application might fail. Additionally I didn't want to do the extra work of creating and exposing interface and a class to replace the structure.
So, I took the code from my form and move it to a public sub in a module. It Worked immediately. By the way, that's how i had implemented the call in the main application which was working ok.
I hope it might help others.
Is there some magic to exposing a
struct to COM for using in VB6?
The article COM Data Types* on MSDN says that structs are supported. Specifically, the MSDN article says that COM structures are defined as:
ByRef VALUETYPE< MyStruct >
There are also a couple of articles on customing your COM-callable wrappers at the bottom of the page, you may wish to review those.
Edit (2016): Original link was broken, so I fixed it to Version 3.5 of the .Net Framework.

Categories

Resources