c# - Lotus Notes c API 问题

标签 c# c pinvoke

各位,我遇到了堆栈不平衡问题,请参见下文

C API 中的 DNParse 函数:

STATUS LNPUBLIC DNParse(DWORD Flags, const char far *TemplateName,
                        const char far *InName, DN_COMPONENTS far *Comp,
                        WORD CompSize);

using FORMULAHANDLE = System.UInt32;
using NullHandle = System.Nullable;
using Status = System.UInt16;
using DBHandle = System.IntPtr;
using DHANDLE = System.IntPtr;
using NoteID = System.UInt32;
using ColHandle = System.UInt32;
using WORD = System.UInt32;
using DWORD = System.UInt32;
using NoteHandle = System.IntPtr;
using FontID = System.UInt32;

public static unsafe string GetCurrentUserCommonName()
    {
        string str = "";
        Status sts = 0;
        DWORD xDWORD = 0;
        dname.DN_COMPONENTS DNComp = new dname.DN_COMPONENTS();            
        StringBuilder szServer = new StringBuilder(0x400, 0x400);
        StringBuilder InName = new StringBuilder(0x400, 0x400);

        Initialize();
        if (m_isInitialized)
        {
            sts = nnotesDLL.SECKFMGetUserName(szServer);                
            sts = nnotesDLL.DNParse(xDWORD, null, szServer, 
                                    DNComp, (Int16)Marshal.SizeOf(DNComp));
            // return CanonName.ToString();
        }
        return str;
    }

以及 C# 版本:

[DllImport("nnotes.dll")]
public unsafe static extern Status DNParse(DWORD Flags, string TemplateName, 
                                           StringBuilder szServer, 
                                           dname.DN_COMPONENTS DNComp,
                                           short CompSize);
DN_COMPONENTS STRUCTURE
public struct DN_COMPONENTS
{
    ....
}

最佳答案

错误是 native 代码期望传递结构的地址。但是您的 C# 代码是按值传递结构的。 p/invoke 应如下所示:

[DllImport("nnotes.dll")]
public static extern Status DNParse(
    DWORD Flags, 
    string TemplateName, 
    string szServer, 
    ref dname.DN_COMPONENTS DNComp,
    short CompSize
);

其他一些要点:

  1. 这里不需要不安全。将其删除。
  2. 两个字符串参数都会传递到函数中,并且缓冲区不会被修改。 const char* 暗示了这一点。因此,将它们编码为字符串

关于c# - Lotus Notes c API 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19193860/

相关文章:

c - c中的unions( union 的内存存储模式)

c++ - 如何在 C/C++ 中从运行时卸载内存偏移量计算?

C 中的常量函数

c# - 在 Windows CE 的 Struct 中编码字符数组

c# - 如何在 C# 中使用 p/invoke 将指针传递给数组?

c# - 获取 .NET 中非托管 dll 导出的 char* 的值

c# - 使用 layoutInflator xamarin 膨胀时出现运行时异常?

c# - 关于如何运行 Selenium 测试以检查网站是否存在的任何建议?

javascript - 父窗口中的 Iframe 的 onSubmit 可以吗?

c# - 使用 Include() 时 Entity Framework 不急于加载