zoukankan      html  css  js  c++  java
  • C\C++ Dll >C# >MaxScript通过C#调用C++写的Dll

    其实是以前博客的老贴子,太久没写博了,就粘贴过来点

    自Max9开始,MaxScript可以直接调用.Net的dll文件,并且可以创建其中的类使用其中的方法。而.Net又可以调用C++编写的dll文件。于是可以使用C#对C++的代码封装一下,在max里调用。以下为范例。

    ---------------以下为dll.def

    LIBRARY "Dll"

    EXPORTS
    HelloWorld @1

    --------------以下为dll.cpp文件内容

    BOOL APIENTRY DllMain( HANDLE hModule,
    DWORD ul_reason_for_call,
    LPVOID lpReserved
    )
    {
    return TRUE;
    }

    void HelloWorld(
    {
    MessageBox( NULL, L"C++ Dll", TEXT("In Win32 DLL"), MB_OK);
    }

    -------以下为c#的封装文件,编译为ImportDll.Dll

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace ImportDll
    {
    public class Win32Dll
    {
    [DllImport("Dll.dll", EntryPoint = "#1")]
    public static unsafe extern void HelloWorld();
    }
    }

    -------------然后可以在MaxScript中如此调用

    DotNet.LoadAssembly (GetFilenamePath (GetSourceFileName()) + "ImportDll.dll")
    (DotNetClass "ImportDll.Win32Dll").HelloWorld()

    ------------------------

    这里我使用了序号导出的方式,如果不想用def文件以序号导出,可以使用 extern "C" 来以C语言的方式将方法导出,之所以这么做是因为C++的导出的方法名会与dll源文件中的名字不符。

    至于为何要用.Net转而不直接用MaxSdk,唯一的好处是,这样可以不受版本限制,不用为各个不同版本建立工程编译。当然这个方法仅限于对max没什么操作的情况下的扩展,如果涉及对Max的操作,就只能老老实实用SDK

  • 相关阅读:
    Best Time to Buy and Sell Stock
    Remove Nth Node From End of List
    Unique Paths
    Swap Nodes in Pairs
    Convert Sorted Array to Binary Search Tree
    Populating Next Right Pointers in Each Node
    Maximum Subarray
    Climbing Stairs
    Unique Binary Search Trees
    Remove Duplicates from Sorted Array
  • 原文地址:https://www.cnblogs.com/sitt/p/2571588.html
Copyright © 2011-2022 走看看