开发者

dll C# AccessViolationException

开发者 https://www.devze.com 2023-03-27 21:23 出处:网络
dll written in Delphi, according to the manual I have to first set the xml path by SET_XML(), then use any function you like.

dll written in Delphi, according to the manual I have to first set the xml path by SET_XML(), then use any function you like.

Delphi functions according the manual:

function SET_XML(var path: PAnsiChar): LongInt; 
function GET_CALCULATION_FAN_ALONE(var fanDescription: PAnsiChar): LongInt;

Use in VB according to the manual:

Public Declare Function SET_XML_PATH Lib "fan.dll" (ByRef path As String) As Long
Public Declare Function GET_CALCULATION_FAN_ALONE Lib "fan.dll" (ByRef path As String) As Long

开发者_开发技巧Sub Main()
    Dim a As Long, b As Long, Str_Result As String, Str_Input As String
    Str_Input = "C:\Users\Sebastiaan\Documents\Visual Studio 2010\Projects\Lucam selectie\Lucam selectie\bin"
    a = SET_XML_PATH(Str_Input)
    Str_Result = "65464;;;1,2;;23;424,8;0,3766;;"
    b = GET_CALCULATION_FAN_ALONE(Str_Result)
End Sub

I did rewrite it in C#

const string _dllLocation = "EbmPapstFan.dll";

[DllImport(_dllLocation)]
public static extern long SET_XML_PATH(ref String path);

[DllImport(_dllLocation)]
public static extern long GET_CALCULATION_FAN_ALONE(ref String fanDescription);

public Main()
{
    String path = @"C:\Users\Sebastiaan\Documents\Visual Studio 2010\Projects\Lucam selectie\Lucam selectie\bin";
    long a = SET_XML_PATH(ref path);

    String fanDescription = "65464;;;1,2;;23;424,8;0,3766;;";
    long c = GET_CALCULATION_FAN_ALONE(ref fanDescription);
}

When running de application I get an AccessViolationException

Attempt to read or write protected memory. This often indicates that other memory is corrupt.

When setting a breakpoint and debugging the code step by step nothing every thing rusn just fine. sometimes i got the error in the debug mode (on line "long c = GET_CALU...")

What am I doing wrong?


I'm not familiar with calling Delphi from C#, but from a quick search it appears that there are some issues with the calling conventions (how values are pushed and popped from the stack). See these threads:

Calling a Delphi DLL from C# produces unexpected results

Calling a delphi DLL method from C# Code

From these, it sounds like it may not be possible to call this directly due to the "fastcall" calling convention. You could try changing the calling convention, that could be worth a quick test. See this page:

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention.aspx

If that doesn't work, I would probably just write a C wrapper DLL that calls the Delphi DLL, and verify that works (make sure it's not just a bug in the DLL). If it does, then you could just call the C DLL from the C# program by using DllImport on your wrapper DLL's function.

Hope that helps a bit,

John

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号