System. AccessViolationException occurred while no real access

Stan Huang 421 Reputation points
2021-02-04T08:41:59.467+00:00

My C# application program calls a C++ DLL and got System. AccessViolationException.
The DLL function snippet in C# are wrapped as below:

class CDllWrapper
{
#region Dll interface
public CDllWrapper() { }
[DllImport("FRV_Dll", //name of the dll
EntryPoint = "Face_Start", //name of function in dll
ExactSpelling = true,
CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl)]
public static extern unsafe int Face_Start();
....
[DllImport("FRV_Dll", //name of the dll
EntryPoint = "Face_Register", //name of function in dll
ExactSpelling = true,
CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.Cdecl)]
public static extern unsafe int Face_Register(CppImportInfo imageData, ref int retCode, ref string retMessage);
.......
#endregion
}

Program snippet in C++ is as follows:

CPLUSPLUS_API int Face_Start()
{
......
}
CPLUSPLUS_API int Face_Register(struct ImportInfo imageData, int
retCode, char** retMessage)
{
try
{
NBiometricClient biometricClient;
NFace face;
return 99;
.....
}*

Calling Face_Start() succeeded. But calling Face_Register(...) got an Exception. I inserted a 'return 99' statement for simplifying the issue. I found even it returns at the beginning, the access violation still occurred. So, why?

The calling sequence at C# program is as below:

......
int retCode = 0;
string retMessage = "";
CppImportInfo importInfo = new CppImportInfo();
importInfo.name = Data_In.name;
.........
importInfo.note = Data_In.note;
try
{
CDllWrapper.Face_Register(importInfo, ref retCode, ref retMessage);
}
catch (Exception Ex)
{
Trace.TraceMessage("[ Exception ] " + Ex.Message, true, ref log_cs);
return Return_Data;
}
......

In my opinion, I returned at the beginning without access to any variables, so why did it happen as Access Violation?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,637 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2021-02-04T09:53:45.97+00:00

    Maybe continue your investigations. Remove all of parameters from Face_Register. This should work.

    Then re-add the ImportInfo parameter. Probably you should use a pointer in C++: ‘ImportInfo * imageData’. Use ‘ref’ in C#: ‘ref CppImportInfo imageData’.

    To avoid confusions, use the “101” button to paste the code here.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful