3,881
社区成员
发帖
与我相关
我的任务
分享
X264ENCODER_API int _stdcall AvcEncode(char* buf, uint8_t* &outdata, int &outdata_size)
{
unsigned long yuvimg_size = Width * Height * 3 / 2;
int x264buf_len = 0;
unsigned char* yuvbuf = (unsigned char*)malloc(yuvimg_size);
unsigned char* x264buf = (unsigned char*)malloc(yuvimg_size * 10);
char* rgbbuf = buf;
if (rgbbuf)
{
RGB2YUV420((LPBYTE)rgbbuf, Width, Height, (LPBYTE)yuvbuf, &yuvimg_size);
bool is_keyframe = false;
Encode(yuvbuf, x264buf, x264buf_len, is_keyframe);
if (x264buf_len > 0)
{
outdata = (uint8_t*)malloc(x264buf_len);//这里申请未释放,造成内存泄漏
memset(outdata, 0, x264buf_len);
memcpy(outdata, x264buf, x264buf_len);
outdata_size = x264buf_len;
}
}
free(x264buf);
x264buf = NULL;
free(yuvbuf);
yuvbuf = NULL;
return true;
}
[DllImport(PATH, CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
[SuppressUnmanagedCodeSecurity]
public static extern int AvcEncode(IntPtr buf, ref IntPtr outdata, ref int outdata_size);
X264ENCODER_API int _stdcall AvcEncode(char* buf, uint8_t* &outdata, int &outdata_size)
{
unsigned long yuvimg_size = Width * Height * 3 / 2;
int x264buf_len = 0;
unsigned char* yuvbuf = (unsigned char*)malloc(yuvimg_size);
unsigned char* x264buf = (unsigned char*)malloc(yuvimg_size * 10);
char* rgbbuf = buf;
if (rgbbuf)
{
RGB2YUV420((LPBYTE)rgbbuf, Width, Height, (LPBYTE)yuvbuf, &yuvimg_size);
bool is_keyframe = false;
Encode(yuvbuf, x264buf, x264buf_len, is_keyframe);
if (x264buf_len > 0)
{
outdata = (uint8_t*)malloc(x264buf_len);
memset(outdata, 0, x264buf_len);
memcpy(outdata, x264buf, x264buf_len);
buf_temp = outdata;//记录申请地址
outdata_size = x264buf_len;
}
}
free(x264buf);
x264buf = NULL;
free(yuvbuf);
yuvbuf = NULL;
return true;
}
下面用于释放内存
X264ENCODER_API void AvcFreeBuf(void)
{
free(buf_temp);
buf_temp = NULL;
}
在C#中调用如下
[DllImport(PATH, CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
[SuppressUnmanagedCodeSecurity]
public static extern int AvcEncode(IntPtr buf, ref IntPtr outdata, ref int outdata_size);
[DllImport(PATH, CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
[SuppressUnmanagedCodeSecurity]
public static extern void AvcFreeBuf();
[DllImport("kernel32.dll")]
public static extern void CopyMemory(IntPtr Destination, IntPtr Source, int Length);
IntPtr _data = IntPtr.Zero;
int _size = 0;
int hr = AvcEncode(buf, ref out_buf, ref out_buf_len);
IntPtr buf_temp = Marshal.AllocHGlobal(out_buf_len);//申请临时空间,存放传出的数据
CopyMemory(buf_temp, out_buf, out_buf_len);//源内存块中的数据复制到新地址:buf_temp
AvcFreeBuf();//释放源内存块:调用动态库中的方法,释放它申请的内存
//这里加入你要操作的代码
if (buf_record != IntPtr.Zero)
{//完成操作后,释放临时空间:buf_temp
Marshal.FreeHGlobal(buf_temp);
buf_temp = IntPtr.Zero;
}