-1

i want to use c++ function code into .net code

MYDLL_API BOOL GetFolderSize(LPCTSTR lpszStartFolder, 
               BOOL bRecurse, 
               BOOL bQuickSize,
               PLARGE_INTEGER lpFolderSize,
               LPDWORD lpFolderCount /*= NULL*/,
               LPDWORD lpFileCount /*= NULL*/);

so i create dll to export the code then use PInvoke in c# code

[StructLayout(LayoutKind.Explicit, Size = 8)]
    struct LARGE_INTEGER
    {
        [FieldOffset(0)]
        public Int64 QuadPart;
        [FieldOffset(0)]
        public UInt32 LowPart;
        [FieldOffset(4)]
        public Int32 HighPart;
    }

  [DllImport("mydll.dll")]
    extern static bool GetFolderSize(string lpszStartFolder,
                               bool bRecurse,
                               bool bQuickSize,
                               out LARGE_INTEGER lpFolderSize,
                                out UInt32 lpFolderCount,
                                out UInt32 lpFileCount);

what the wrong in that????

but when i call it it give me run time exception A call to PInvoke function 'dublication!dublication.Form1::GetFolderSize' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature

1 Answers1

0

Two problems I see:

  • Calling convention: The default calling convention of P/Invoke is WINAPI. Depending on what MYDLL_API is, you might need to do something like [[DllImport("mydll.dll", CallingConvention = CallingConvention.Stdcall)]]

  • String type -- LPCTSTR is not the default string conversion.

The full declaration will look something like...

[DllImport("mydll.dll", CallingConvention = CallingConvention.Stdcall)]
extern static int GetFolderSize(
    [MarshalAs(UnmanagedType.LPStr)] string lpszStartFolder,
    int bRecurse,
    int bQuickSize,
    out long lpFolderSize,
    out uint lpFolderCount,
    out uint lpFileCount);

If you post what MYDLL_API is, we'll have a better sense. Also, if you're not averse to adding unsafe to everything, I've found it makes working with pointers/out parameters/etc much easier.

Robert Fraser
  • 10,649
  • 8
  • 69
  • 93
  • i will write it – falcon eagle Sep 28 '16 at 19:50
  • i am sorry if i do not understand this c++ function how can i declare it in c# via pinvoke __declspec(dllexport) BOOL GetFolderSize(LPCTSTR lpszStartFolder, BOOL bRecurse, BOOL bQuickSize, PLARGE_INTEGER lpFolderSize, LPDWORD lpFolderCount /*= NULL*/, LPDWORD lpFileCount /*= NULL*/); – falcon eagle Sep 29 '16 at 18:11