Click here to Skip to main content
15,887,815 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I am trying to use a third party native dll. in my .net application. I am using c#. The function in native dll. has the following declaration:

void _stdcall pir_learnCCF( const char * serial, unsigned char state );


With the PInvoke Interop assistant I get the following import:

C#
[DllImport("PIRLIB.dll", EntryPoint = "pir_learnCCF")]
public static extern void pir_learnCCF(
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPStr)] string serial, 
byte state);


I have the following questions. When using PInvoke interop assistant I have to remove the "_stdcall" from unmanaged function definition, otherwise the assistant generates an error. After I remove the "_stdcall" the assistant generates the above using sentence but when I try to call the function I get the PInvokeStackUnbalance detected. The third party dll. has other functions which work normally with import sentences generated by the Interop Assistant. Any advice will be appreciated.

Uroš
Posted

1 solution

First, the parameters are correct. You don't even need to use MarshalAs for string, as this marshaling is the default. (By the way, it is allowed and recommended to omit "Attribute" from names like "MarshalAsAttribute" at the place of attribute application.)

The only reason of unbalance stack I could possibly see is calling convention. In this case, it could be C (first calling conventions candidate). So, try this first:

C#
DllImport("PIRLIB.dll", EntryPoint = "pir_learnCCF", CallingConvention = CallingConvention.Cdecl)]
public static extern void pir_learnCCF(string serial, byte state);


See:
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.callingconvention.aspx[^],
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention.aspx[^].

—SA
 
Share this answer
 
Comments
koleraba 15-Dec-11 15:46pm    
Hi
Thank you for your reply. About the attributes: I know you can omit the Attribute when declaring an attribute but the code was generated by a tool(PInovke interop assistant). I already tried to set the CallingConvention to Cdecl but it did not help. However I did found out that if I change the target framework to 3.5 or lower(currently I am using .net 4) that solves the problem. Any other ideas will be appreciated

Uroš

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900