cpp
// HSProcWrapper.h
#pragma once
#include "HSProc.h"
#include <msclr/marshal_cppstd.h>
using namespace System;
using namespace System::Threading::Tasks;
using namespace System::Runtime::InteropServices;
namespace HSManaged
{
public ref class HSProcWrapper
{
private:
HSProc* nativeProc;
ref struct InitContext
{
TaskCompletionSource<bool>^ tcs;
};
static void NativeCallback(
int retCode,
const char* errMsg,
void* userData)
{
GCHandle handle = GCHandle::FromIntPtr(IntPtr(userData));
InitContext^ ctx = (InitContext^)handle.Target;
handle.Free();
if (retCode == 0)
{
ctx->tcs->SetResult(true);
}
else
{
String^ msg = gcnew String(errMsg);
ctx->tcs->SetException(
gcnew InvalidOperationException(msg)
);
}
}
public:
HSProcWrapper()
{
nativeProc = new HSProc();
}
~HSProcWrapper()
{
this->!HSProcWrapper();
}
!HSProcWrapper()
{
delete nativeProc;
nativeProc = nullptr;
}
/// <summary>
/// await 版本初始化
/// </summary>
Task^ InitAsync(
int bitdepth,
String^ maskfile,
CAMTYPE camera,
int maskRoiX,
int maskRoiY,
int maskRoiWidth,
int maskRoiHeight)
{
auto tcs = gcnew TaskCompletionSource<bool>();
auto ctx = gcnew InitContext();
ctx->tcs = tcs;
GCHandle handle = GCHandle::Alloc(ctx);
std::wstring nativeMask =
msclr::interop::marshal_as<std::wstring>(maskfile);
nativeProc->initAsync(
bitdepth,
nativeMask,
camera,
maskRoiX,
maskRoiY,
maskRoiWidth,
maskRoiHeight,
&NativeCallback,
GCHandle::ToIntPtr(handle).ToPointer()
);
return tcs->Task;
}
};
}
WPF调用
csharp
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
await _proc.InitAsync(
16,
"mask.png",
CAMTYPE.CAM_A,
0, 0, 0, 0
);
MessageBox.Show("初始化完成");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
参考;
https://chatgpt.com/share/6943c959-0564-8008-8deb-afe5523c07c1