TypeBuilder.DefinePInvokeMethod

  • Thread starter Thread starter Claire
  • Start date Start date
C

Claire

I've now found out how to approach calling the functions of dynamically
loaded dlls. Ive never looked at interop so I don't understand a thing I'm
doing but I am trying to adapt someone elses example code for my own needs.
My first attempt was for a function that expected no parameters. I did it in
a similar way to the following. This one worked ok.
The following code is meant to define the function "int Connect(pChar URL)".
I know I've to create an array of types which represents the parameters but
I don't know if I use the "typeof(string)" to represent a pChar.
Can someone help please.
Also, some of the functions defs I'll be creating will expect pointers to
some defined structs. How would I do this.? See end for struct example.

/////////////
// Connect //
/////////////
Type[] myConnectType = {typeof(string)};
methodbuilder = typebuilder.DefinePInvokeMethod(
"tsrConnect",
DllFileName,
MethodAttributes.Public | MethodAttributes.Static |
MethodAttributes.PinvokeImpl,
CallingConventions.Standard,
typeof(int),
myConnectType,
CallingConvention.StdCall,
CharSet.Auto);


A struct, supposedly representing a packed record. Don't know if Ive done
the char[30] bit correctly.
[ StructLayout( LayoutKind.Sequential, Pack = 1 )]
public struct TtsrChannelInfo
{
public int ChannelID;
public int ChannelParentID;
public int PlayerCountInChannel;
public int ChannelFlags;
public int Codec;
[MarshalAs( UnmanagedType.ByValArray, SizeConst=30 )]
public char[] Name;
}
 
The following code is meant to define the function "int Connect(pChar URL)".
I know I've to create an array of types which represents the parameters but
I don't know if I use the "typeof(string)" to represent a pChar.

That may work, yes. The easiest way to know would be to write a
DllImport method in C# and make sure that works, then translate it to
the corresponding Reflection Emit code.

Also, some of the functions defs I'll be creating will expect pointers to
some defined structs. How would I do this.? See end for struct example.

In a C# method signature you'd make it a ref struct parameter. With
Reflection that maps to a ByRef type, which you in v1.x get with
Type.GetType() by appending & to the type name. For example

Type channelInfoByRefType = Type.GetType("TtsrChannelInfo&,
SomeAssembly");

In Whidbey you can instead do

typeof(TtsrChannelInfo).MakeByRefType()



Mattias
 
Back
Top