访问冲突C ++ / CLI

时间:2012-02-13 09:57:18

标签: c++-cli

我正在为原生第三方库制作C ++ / CLI包装器,代码如下:

#pragma once
#include <Codegen.h>
#include <string>
using namespace System;

namespace CodegenWrapper {

    public ref class CodegenWrapper
    {
    private:
        Codegen * codegen;
    public:     
        CodegenWrapper(array<float>^ pcm, uint numSamples, int start_offset)
        {   
            float* audio = new float[pcm->Length];
            for (int i = 0; i < pcm->Length; i++)
            {
                audio[i] = (float)pcm[i];
            }
            codegen = new Codegen(audio,numSamples,start_offset);
        }

        String^ GetCodeString(){ return  gcnew String(codegen->getCodeString().c_str());}


        int GetNumCodes(){return codegen->getNumCodes();}

        float GetVersion() { return codegen->getVersion(); }

        ~CodegenWrapper(){delete codegen;}
    };
}

即使对Dispose:

进行了更改,这也是例外
System.AccessViolationException was unhandled
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=CodegenWrapper
  StackTrace:
       at delete(Void* )
       at std.basic_string<char,std::char_traits<char>,std::allocator<char> >._Tidy(basic_string<char\,std::char_traits<char>\,std::allocator<char> >* , Boolean _Built, UInt32 _Newsize) in c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0:line 588
       at CodegenWrapper.CodegenWrapper.GetCodeString() in c:\program files (x86)\microsoft visual studio 11.0\vc\include\xstring:line 962
       at ConsoleApplication2.Program.Main(String[] args) in c:\Users\galvesribeiro\Desktop\Econest\ConsoleApplication2\Program.cs:line 47
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

调用GetCodeString()时,我收到了访问冲突。

应该是什么问题?

1 个答案:

答案 0 :(得分:1)

很难说,这可能发生在本机代码中。然而你的包装不完美。您没有适当地防止客户端代码过早地处理包装器。一个错误的使用语句就足以使AccessViolation绊倒。您还忘记了终结器,当客户端代码忘记处置时,需要避免永久性泄漏。看起来像这样:

    ~CodegenWrapper() {
        delete codegen;
        codegen = 0;
    }

    !CodegenWrapper() {
        delete codegen;
    }

    int GetNumCodes() {
        if (!codegen) throw gcnew ObjectDisposedException("CodegenWrapper");
        return codegen->getNumCodes();
    }

也将处理后的测试添加到其他成员。