Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c++ cli - Passing a CLI/C++ array to a C function

I need to call C functions from C#. I have created a C++/CLI wrapper to load the DLL and call the relevant functions. All the C functions in the DLL have been exported.

C Code ( Configration - Win32 )

double getAverage(double* arr, int size) 
{
    ... more code .. 
    return average;
}

C# Code ( Configration - x86) Using Any CPU displays a warning.

Bridge bridge = new Bridge();
double[] balance = new double[5] { 1000, 2, 3, 17, 50 };
bridge.Average(balance, 5);

C++/CLI Code ( Configration - Win32 )

HMODULE hDllModule ;

Bridge::Bridge()
{
  hDllModule = LoadLibrary(TEXT("TestLibrary.dll"));
}

Bridge::~Bridge()
{
  if (hDllModule)
     FreeLibrary(hDllModule);
}

double Bridge::Average(array<double>^ values, int ^size)
{
  typedef double(__cdecl* PFNAVG)(double* numbers, int size);
  PFNAVG pfnAvg;
  
  pfnAvg = (PFNAVG)GetProcAddress(hDllModule, "getAverage");
  
  pin_ptr<double> pPinArrayValues = &values[0];
  double* pPinPtrAdress = pPinArrayValues;
  
  double avg = pfnAvg(pPinPtrAdress, values->Length);
  
  return avg;
}

I am receiving a runtime error

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

at double avg = pfnAvg(pPinPtrAdress, values->Length);

There is a similar question ; in my case I am using a function pointer to call the C function.

Please point me what I am doing wrong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...