【问题标题】:How call method from custom .net dll in vbscript如何在 vbscript 中从自定义 .net dll 调用方法
【发布时间】:2016-12-24 17:33:27
【问题描述】:

我可以管理 dll。此 dll 包含返回自定义结构等方法。

方法和结构

    [DllImport("powrprof.dll")]
            private static extern uint CallNtPowerInformation(
                int InformationLevel,
                IntPtr lpInputBuffer,
                int nInputBufferSize,
                ref SystemPowerInformation spi,
                int nOutputBufferSize
            );

public SystemPowerInformation GetSystemPowerInformation()
        {
            SystemPowerInformation spi = new SystemPowerInformation();

            CallNtPowerInformation(12,
                IntPtr.Zero,
                0,
                ref spi,
                Marshal.SizeOf(spi));

            return spi;
        }

[ComVisible(true)]
    [StructLayout(LayoutKind.Sequential)]
    [Guid("A79B0F9F-00C7-46C8-A3AE-D371E09ADB0C")]
    public struct SystemPowerInformation
    {
        public uint MaxIdlenessAllowed;
        public uint Idleness;
        public uint TimeRemaining;
        public byte CoolingMode;
    }

VbScript

set calc = CreateObject("PowerStateManagement.PowerStateManagement")

sleepTime = calc.GetLastSleepTime()
WScript.Echo(sleepTime)

wakeTime = calc.GetLastWakeTime()
WScript.Echo(wakeTime)

spi = calc.GetSystemPowerInformation()

WScript.Echo(spi.TimeRemaining)

运行此脚本时出现异常。

0x800a01a8 - Microsoft VBScript 运行时错误:需要对象:'spi'

但如果 GetSystemPowerInformation 方法重写为 return spi.TimeRemaining则此脚本返回正确的 TimeRemaining

为什么我不能返回结构,只有结构的字段?

【问题讨论】:

  • 您只是缺少set 关键字吗?即Set spi = calc.GetSystemPowerInformation()

标签: c# dll vbscript com interop


【解决方案1】:

VBScript 只支持 Variant 类型,而 Variant 类型不支持结构。给spi赋值后,VarType(spi)的结果是什么?如果它是一个字节数组,您可以获取代表 TimeRemaining 值的 4 个字节并尝试将它们转换为 uint。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多